3

I use angularjs (ng-init) and I want to assign value to variable as jsonObj.

I try this one but it doesn't work.

ng-init="percentObj = [{ "value":40,"color":"#F5A623" },{ "value":60,"color":"#F5A623" }];

and another question I want to assign value like

percentObj = [{ "value": parseInt($scope.projectData[0].value),"color":"#F5A623" },{ "value":  parseInt($scope.projectData[0].value),"color":"#F5A623" }]

How to fix this problem??

Thx

user3900567
  • 31
  • 1
  • 1
  • 3

5 Answers5

2

You can use window object for set your json :

<script type="text/javascript">
    window.data= {awesome:1};
</script>

view :

<div ng-controller="myCntrl" ng-init="init('data')">

controller :

function myCntrl($scope) {
   $scope.init = function (settings) {
      settings = window[settings];
      console.log(settings.awesome); //1
   };
}
Nigrimmist
  • 10,289
  • 4
  • 52
  • 53
1

Escape your quotes...

ng-init="percentObj = [{ \"value\":40,\"color\":\"#F5A623\" },{ \"value\":60,\"color\":\"#F5A623\" }];"
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Can I replace 40 with varialble?\ – user3900567 Sep 03 '14 at 13:41
  • I would recommend not initialize code in the view. From my point of view must be inside the controller, even more if you need to access variables for other objects. The view must be kept as simple as possible. – Kaken Sep 03 '14 at 14:02
0

Try this...

    <body ng-controller="TestController">
       <div ng-init="Init()">
        {{percentObj || json }}
       </div>
    </body>

    $scope.Init = function()
    {
      $scope.percentObj = [{ "value":40,"color":"#F5A623" },{ "value":60,"color":"#F5A623"                }]
    }
Kaken
  • 163
  • 5
  • 9
0

Just have a JSON encoded string in some element's attribute and then catch that with Angular.

HTML

<div data-config="{title:'this is my title'}" my-directive></div>

AngularJS:

app.directive('myDirective', function () {
    return {
        restrict: 'A',
        link: function (scope, element) {

            // apply config from element's data-config attribute
            scope.config = element.data('config');

            // print out the data in console
            console.log(scope.config);

        }
    };
});

Can be done without jQuery too, then the .data('config') part changes.

Esamo
  • 111
  • 4
-1

for second one, Please check the code below

var obj = {};
$scope.percentObj = [];
obj.value = parseInt($scope.projectData[0].value);
obj.color = "#F5A623";
$scope.percentObj.push(obj);
sameer
  • 320
  • 3
  • 14