[英]How to let the angularjs controller run only once even many ng-controllers defined in DOM?
I wish I can handle this, but in the bad way...namely I need to use $cookieStore
to check either the function called or not. 我希望我能解决这个问题,但是以一种糟糕的方式...也就是说,我需要使用$cookieStore
来检查是否调用了该函数。
Every time to use push
array then I need to use $cookieStore
. 每次使用push
array时,我都需要使用$cookieStore
。 But it seems not practical. 但这似乎不切实际。
Here was my DOM: 这是我的DOM:
<div ng-controller="MyCtrl">
<div>
<div ng-include="'temp2.html'">
Hello, {{name}}!
</div>
</div>
</div>
<script type="text/ng-template" id="temp2.html">
<div ng-controller="MyCtrl">Another View</div>
</script>
And my angularjs controller: 还有我的angularjs控制器:
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
alert(1);
}
alert(1)
function will be called 2 times every times the page was called. 每次调用该页面时,都会两次调用alert(1)
函数。
How to avoid this problem without using watcher? 如何在不使用观察程序的情况下避免此问题?
The controller would called be twice for both the views, i would suggest you to move controller
specific code to init
function and use ng-init
in one of your views
. 对于这两个视图,控制器将被调用两次,我建议您将controller
特定的代码移至init
函数,并在其中一个views
使用ng-init
。
var Controller = function($scope) {
$scope.init = function () {
};
};
Your View 您的看法
<div ng-controller="Controller" ng-init="init()"/>
Yo don't need to specify the Controller name again in the include.... if its the same as the parent one(same as controller of main page). 如果与父名称相同(与主页的控制器相同),则无需在include ....中再次指定控制器名称。
just go with this 随这个去吧
<div ng-controller="MyCtrl">
<div>
<div ng-include="'temp2.html'">
Hello, {{name}}!
</div>
</div>
</div>
<script type="text/ng-template" id="temp2.html">
<div>Another View {{name}}</div>
</script>
name will be accessible in the view you included. 名称将在您包括的视图中访问。
Hope it will help you.. 希望对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.