Inject variables via ng-init to controller

喜你入骨 提交于 2019-12-12 07:22:25

问题


I want to inject the same variables with different values multiples times to the same controller. This is what I tried. What is a way to get different values in each call?

HTML

<body ng-app="myApp">
    <div ng-controller="myCtrl" ng-init="test='helloworld';test1='helloworld2'">

    </div>
    <div ng-controller="myCtrl" ng-init="test='helloworld3';test1='helloworld4'">

    </div>
    <div ng-controller="myCtrl" ng-init="test='helloworld5';test1='helloworld6'">

    </div>
<body>

JavaScript code

var app = angular.module("myApp", []);

app.controller("myCtrl", ["$scope",function($scope) {
    console.log($scope.test);
    console.log($scope.test1);
}]);

回答1:


ng-init Docs says:

This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope.

You shouldn't assign init values using ng-init. The correct way to do it would be to assign at the end on AngularJS controller function.

Technically, what happening is that the ng-init directive gets evaluated after the ng-controller function gets registered. That's why initialized values from the ng-init are not available inside the controller.

Basically, the reason behind ng-controller getting called first is the priority. If you look at the priority, the ng-init directive has 450 & the priority option of directive, where ng-controller directive has 500, while compiling the directive from the DOM AngularJS sorts them as per priorities. Thus ng-controller gets executed first.

Code

var app = angular.module("myApp", []);

app.controller("myCtrl", ["$scope",function($scope) {
    console.log(test);
    console.log(test1);

    // If you wanted to assign the values dynamically you could make Ajax here
    // that would call the server-side method which will return the values
    // and in success that Ajax you could set those scope values.
    // If any dependent function should get called after assigning them.
    // Then you can call that function from that Ajax success.
    $http.get('/getDefaultValues').then(function(response){
        var data = response.data;
        $scope.test= data.value1;
        $scope.test1 = data.value2;
    });
}]);

Edit

As it seems like above code wouldn't be possible to do because variable values are assigning from jsp/aspx page. For such reason I'd suggest another way of achieving this. I think that is more cleaner way of doing it.

I'd suggest you do initialize you angular app lazily by using angular.bootstrap rather than using ng-app which initialize app as soon as page loads.

angular.element(document).ready(function() {
  angular.bootstrap(document, ['TodoApp']);
});

Now you will think like how could it solve the problem of assigning the variable to the scope before making controller available, for that case you could create a value object and assign the variable which are populating on jsp/aspx page the value (kind of service)

<script type="text/javascript">
    angular.element(document).ready(function() {
      //like below you could get value inside your app by assigning
      //to some angular component like constant/value
      angular.module('TodoApp').value('sharedData', {
          'test': @myValueFromAspxPage,
          'test1': @myValueFromAspxPage1
      });
      angular.bootstrap(document, ['TodoApp']);
    });
</script>

By doing above thing you could easily make available your values inside a controller, & then no need to wait until one digest cycle to complete using $timeout. You could use this values inject inside sharedData value by injecting inside a controller.




回答2:


Try this... As @tymeJV pointed out you need to use semicolons to separate the variable names in the HTML. You also need to use the $scope to reference the variables in the controller.

html

<body ng-app="myApp">     
    <div ng-controller="myCtrl" ng-init="test='helloworld';test1='helloworld2'">

    </div>
    <div ng-controller="myCtrl" ng-init="test='helloworld3';test1='helloworld4'">

    </div>
    <div ng-controller="myCtrl" ng-init="test='helloworld5';test1='helloworld6'">

    </div>
<body>

javascript

var app = angular.module("myApp", []);

app.controller("myCtrl", ["$scope",function($scope) {
    console.log($scope.test);
    console.log($scope.test1);
}]);



回答3:


Found a dirty fix. Thanks all for your inputs.

Demo

var app = angular.module("myApp", []);

app.controller("myCtrl", ["$scope", '$timeout',function($scope, $timeout) {
    $timeout(function(){ 
        console.log($scope.test);
        console.log($scope.test1);  
    }, 1);
}]);


来源:https://stackoverflow.com/questions/33285606/inject-variables-via-ng-init-to-controller

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