ng-init json Object

落花浮王杯 提交于 2019-12-23 20:09:33

问题


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


来源:https://stackoverflow.com/questions/25644936/ng-init-json-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!