简体   繁体   English

通过 ng-init 向控制器注入变量

[英]Inject variables via ng-init to controller

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 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 JavaScript 代码

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

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

ng-init Docs says: ng-init文档说:

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; ngInit 只有几个合适的用途,例如为 ngRepeat 的特殊属性设置别名,如下面的演示所示; 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.除了这几种情况之外,您应该使用控制器而不是 ngInit 来初始化范围上的值。

You shouldn't assign init values using ng-init .您不应该使用ng-init分配 init 值。 The correct way to do it would be to assign at the end on AngularJS controller function.正确的做法是在最后分配 AngularJS controller函数。

Technically, what happening is that the ng-init directive gets evaluated after the ng-controller function gets registered.从技术上讲,发生的事情是在注册ng-controller函数后对ng-controller ng-init指令进行评估。 That's why initialized values from the ng-init are not available inside the controller.这就是ng-init初始化值在控制器内部不可用的原因。

Basically, the reason behind ng-controller getting called first is the priority.基本上,首先调用ng-controller的原因是优先级。 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.如果您查看priorityng-init指令有450和指令的priority选项,其中ng-controller指令有500 ,而从 DOM AngularJS编译指令时,会根据优先级对它们进行排序。 Thus ng-controller gets executed first.因此ng-controller首先被执行。

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.上面的代码似乎无法执行,因为变量值是从jsp / aspx页面分配的。 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.bootstrap而不是使用ng-app来初始化你的 angular 应用ng-app ,它会在页面加载后立即初始化应用程序。

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)现在你会想它如何解决在使控制器可用之前将变量分配给作用域的问题,在这种情况下,你可以创建一个值对象并为在jsp / aspx页面上填充的变量分配value (服务类型)

<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 .通过执行上述操作,您可以轻松地在控制器中提供您的值,然后无需等待使用$timeout完成一个摘要周期。 You could use this values inject inside sharedData value by injecting inside a controller.您可以通过注入控制器内部来使用此值注入到sharedData值中。

Try this... As @tymeJV pointed out you need to use semicolons to separate the variable names in the HTML.试试这个...正如@tymeJV 指出的那样,您需要使用分号来分隔 HTML 中的变量名称。 You also need to use the $scope to reference the variables in the controller.您还需要使用$scope来引用控制器中的变量。

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

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM