两次打击 AngularJS 执行控制器 [英] Combating AngularJS executing controller twice
问题描述
我知道 AngularJS 会运行一些代码两次,有时甚至更多,比如 $watch
事件,不断检查模型状态等.
但是我的代码:
function MyController($scope, User, local) {var $scope.User = local.get();//获取本地保存的用户数据User.get({ id: $scope.User._id.$oid }, function(user) {$scope.User = 新用户(用户);本地.save($scope.User);});//...
执行两次,将 2 条记录插入到我的数据库中.很明显,我仍在学习,因为我多年来一直在努力解决这个问题!
应用路由器指定导航到 MyController
像这样:
$routeProvider.when('/',{ templateUrl: 'pages/home.html',控制器:MyController });
但我在 home.html
中也有这个:
这两次消化了控制器.从 HTML 中删除 data-ng-controller
属性解决了这个问题.或者,可以从路由指令中删除 controller:
属性.
使用标签式导航时也会出现此问题.例如,app.js
可能包含:
.state('tab.reports', {网址:'/报告',意见:{标签报告":{templateUrl: 'templates/tab-reports.html',控制器:'ReportsCtrl'}}})
相应的报告选项卡 HTML 可能类似于:
<ion-content ng-controller="ReportsCtrl">
这也会导致控制器运行两次.
I understand AngularJS runs through some code twice, sometimes even more, like $watch
events, constantly checking model states etc.
However my 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);
});
//...
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!
解决方案 The app router specified navigation to MyController
like so:
$routeProvider.when('/',
{ templateUrl: 'pages/home.html',
controller: MyController });
But I also had this in home.html
:
<div data-ng-controller="MyController">
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.
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'
}
}
})
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屋!
查看全文