[英]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.