打击AngularJS执行控制器两次 [英] Combating AngularJS executing controller twice
问题描述
我明白AngularJS通过一些$ C $运行c两次,有时甚至更多,比如$手表活动,不断检查模型状态等。
I understand AngularJS runs through some code twice, sometimes even more, like $watch events, constantly checking model states etc.
不过我的code:
function MyController($scope, User, local) {
var $scope.User = local.get(); // Get locally save user data
User.get({ id: $scope.User._id.$oid }, function(user) {
$scope.User = new User(user);
local.save($scope.User);
});
//...
执行两次,插入2条记录到我的数据库。我清楚地还在学习,因为我一直在敲我的头这时代!
Is executed twice, inserting 2 records into my DB. I'm clearly still learning as I've been banging my head against this for ages!
推荐答案
像这样指定的导航 myController的
的应用路由器:
The app router specified navigation to MyController
like so:
$routeProvider.when('/',
{ templateUrl: 'pages/home.html',
controller: MyController });
不过,我也有过这样的 home.html的
:
<div data-ng-controller="MyController">
这消化控制器的两倍。删除数据-NG-控制器
从HTML属性解决了这个问题。另外,控制器:
财产可能已经从路由指令删除
This digested the controller twice. Removing the data-ng-controller
attribute from the HTML resolved the issue. Alternatively, the controller:
property could have been removed from the routing directive.
使用标签式浏览的时候,也会出现此问题。例如, app.js
可能包含:
This problem also appears when using tabbed navigation. For example, app.js
might contain:
.state('tab.reports', {
url: '/reports',
views: {
'tab-reports': {
templateUrl: 'templates/tab-reports.html',
controller: 'ReportsCtrl'
}
}
})
相应的报告选项卡的HTML可能类似于:
The corresponding reports tab HTML might resemble:
<ion-view view-title="Reports">
<ion-content ng-controller="ReportsCtrl">
这也将导致运行控制器的两倍。
This will also result in running the controller twice.
这篇关于打击AngularJS执行控制器两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!