ng-init
文件说:
该指令可能被滥用以添加不必要的逻辑量
你的模板。 ngInit 只有几种合适的用途,例如
至于 ngRepeat 的特殊属性别名,如演示中所示
以下;以及通过服务器端脚本注入数据。除了这些
少数情况下,您应该使用控制器而不是 ngInit 来初始化
范围内的值。
您不应该使用分配初始值ng-init
。正确的方法是在 AngularJS 的末尾进行赋值controller
功能。
从技术上讲,发生的事情是ng-init
指令在之后被评估ng-controller
函数被注册。这就是为什么初始化值来自ng-init
在控制器内部不可用。
基本上,背后的原因ng-controller
首先接到电话是优先事项。如果你看一下priority
, the ng-init
指令有450
& 这priority
指令的选项,其中ng-controller
指令有500
,同时从 DOM 编译指令AngularJS http://en.wikipedia.org/wiki/AngularJS根据优先级对它们进行排序。因此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
看来上面的代码是不可能执行的,因为变量值是从jsp
/aspx
页。出于这个原因,我建议采用另一种方法来实现这一目标。我认为这是更干净的方式。
我建议您使用以下方式延迟初始化您的角度应用程序angular.bootstrap
而不是使用ng-app
页面加载后立即初始化应用程序。
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
。您可以在里面使用这个值注入sharedData
通过注入控制器内部来获取值。