-->

ng-init json Object

2019-07-13 01:37发布

问题:

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

回答1:

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
   };
}


回答2:

Escape your quotes...

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


回答3:

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"                }]
    }


回答4:

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.



回答5:

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);