[英]Initialize data with init() call or ng-init?
在我的AngularJS应用中,我必须在加载时初始化一些值。
我在这种情况下编写了一个函数init()
。
function init() {
this.var = 'example';
}
在我的JS脚本末尾或使用ng-init
属性调用init
函数更好吗?
解决方案1
/* script.js */
function init() { /* instructions */ }
init();
解决方案2
/* script.js */
function init(){ // instructions // }}
// Not calling init() here
<!-- file.html -->
<div ng-controller="exampleCtrl as example" ng-init="example.init()">
如果这将初始化一些值以准备使用它们的页面,那么您将使用控制器,对吗? 所以为此使用内置方法$ onInit() ...
$onInit() {
$scope.foo = 'some value';
// Initialise other variables;
}
AngularJS 1.5中为组件控制器添加了$ onInit() ,但它可用于所有控制器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.