Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combating AngularJS executing controller twice

Tags:

angularjs

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!

like image 413
Greg Avatar asked Mar 20 '13 21:03

Greg


People also ask

Can we have two controllers in AngularJS?

Angular creates one $scope object for each controller. We also have a $rootScope accessible from every controllers.In case of multiple controllers AngularJS framework creates and pass a different $scope object to each controller so that data and methods of one controller not be accessed in another controller.

Can we have nested controller in AngularJS?

Nested Controllers: AngularJS allows using nested controllers. It means that you have specified a controller in an HTML element which is a child of another HTML element using another controller.

What is the responsibility of the controller in AngularJS?

The primary responsibility of an AngularJS Controller is to control the data that gets passed to the view. There is two-way communication between the scope and the view .

How pass data from controller controller to AngularJS?

Approach: To share data between the controllers in AngularJS we have two main cases: Share data between parent and child: Here, the sharing of data can be done simply by using controller inheritance as the scope of a child controller inherits from the scope of the parent controller.


1 Answers

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.

like image 197
Greg Avatar answered Oct 16 '22 20:10

Greg