通过ng-init向控制器注入变量
Inject variables via ng-init to 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);
}]);
ng-init
医生说:
这个指令可能被滥用,在你的模板。只有少数几种合适的ngInit用法,例如如演示中所示,用于混叠ngRepeat的特殊属性下面的;以及通过服务器端脚本注入数据。除了这些在少数情况下,应该使用控制器而不是ngInit来初始化
你不应该使用ng-init
分配init值。正确的方法是在AngularJS的最后分配controller
函数。
从技术上讲,发生的事情是ng-init
指令在ng-controller
函数注册后得到评估。这就是为什么ng-init
的初始化值在控制器中不可用的原因。
基本上,ng-controller
首先被调用的原因是优先级。如果你看priority
, ng-init
指令有450
&指令的priority
选项,其中ng-controller
指令有500
,当从DOM编译指令时,AngularJS根据优先级对它们进行排序。因此,ng-controller
首先被执行。
代码
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;
});
}]);
编辑
因为上面的代码似乎不可能做到,因为变量值是从jsp
/aspx
页面分配的。因此,我建议采用另一种方法来实现这一目标。我认为那是更干净的方法。
我建议你使用angular.bootstrap
来初始化你的angular应用程序,而不是使用ng-app
, CC_18会在页面加载时初始化应用程序。
angular.element(document).ready(function() {
angular.bootstrap(document, ['TodoApp']);
});
现在你会想,在使控制器可用之前,它如何解决将变量分配给作用域的问题,对于这种情况,你可以创建一个值对象并将填充在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>
通过做上面的事情,你可以很容易地在控制器中使用你的值,&然后不需要等到一个消化循环使用$timeout
完成。
试试这个…正如@tymeJV指出的那样,您需要使用分号来分隔HTML中的变量名。您还需要使用$scope
来引用控制器中的变量。