角:NG-init不会对负载运行 [英] Angular : ng-init does not run on load
问题描述
我看到的这个NG-初始化问题堆栈溢出几个exmaples,但我似乎无法找到一个这与使用控制器的引用它。
I have seen a few exmaples on stack overflow about this ng-init issue, although I cant seem to find one which references it with the use of a controller.
我已经有在HTML文件中的以下称为控制器功能
I have called the function in the controller by having the following in the html file
<div class="tab-container" ng-controller = "ExampleController" ng-init = "init()" >
在控制器:
$scope.init = function(){
alert("do something");
};
它不运行,但它运行的组件已加载在屏幕上了。
It does run, but it runs before the components have loaded on the screen.
我这么想吗?
感谢
推荐答案
NG-INIT
应该是这样的工作,因为它用来初始化数据。
ng-init
is supposed to work like this, because it's used to initialize data.
有一个很简单的例子:
<ul ng-init="list = [1,2,3,4]">
<li ng-repeat="l in list"></li>
</ul>
如果你想运行的的东西的同时,控制器的负载,它比你想象居然要简单得多:
If you are trying to run something while your controller loads, it's actually much simpler than you thought:
app.controller('mainCtrl', function ($scope) {
var init = function ($scope) {
// do whatever you need to do to initialize your controller
$scope.someData = ["Hey", "I'm", "Alive"]
$scope.otherData = localStorage.getItem('myBackup')
}
init()
})
或者更简单,如果你不需要的功能(没有倒闭或其他)
Or even simpler, if you don't need the function (no closures or whatever)
app.controller('mainCtrl', function ($scope) {
// do whatever you need to do to initialize your controller
$scope.someData = ["Hey", "I'm", "Alive"]
$scope.otherData = localStorage.getItem('myBackup')
})
编辑 - 假设你使用 ngView
:结果
要对当页面完全加载,你应该设置一个观察者对事件code运行 $ viewContentLoaded
,就像这样:
Edit - assuming you're using ngView
:
To have the code run on when the page is fully loaded you should set a watcher on the event $viewContentLoaded
, like this:
$scope.$on('$viewContentLoaded', function(){
//Here your view content is fully loaded !!
});
app.controller('mainCtrl', function ($scope) {
// This event is triggered when the view has finished loading
$scope.$on('$viewContentLoaded', function() {
$scope.someData = ["Hey", "I'm", "Alive"]
$scope.otherData = localStorage.getItem('myBackup')
})
})
这篇关于角:NG-init不会对负载运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!