A
A
Alex2015-12-07 23:52:24
JavaScript
Alex, 2015-12-07 23:52:24

Why does AngularJS controller fire twice?

There is a controller with the following content

app.controller("ProductListCtrl", ['$scope', 'Products', 'Product', function($scope, Products, Product) {
  console.log("ProductListCtrl");
  $scope.sortType      = 'name';
  $scope.sortReverse   = false;
  $scope.searchProduct = '';
  $scope.products = Products.query();
  $scope.deleteProduct = function (id) {
    if (confirm("Are you sure you want to delete this Product?")){
      console.log(id);
      Product.delete({id: id}, function(){
        $scope.products = Products.query();
      });
    }
  }
}]);

And every time when it works (except the first one) console.log("ProductListCtrl"); is displayed in the console 2 times.
Why???
Here are more routes
'use strict';

var app = angular.module('app', ['ngRoute', 'ngResource']); 

//Routes
app.config([
  '$routeProvider', function($routeProvider, $locationProvider) {
    $routeProvider
    .when('/', {
      templateUrl: 'templates/index.html',
      controller: 'ProductListCtrl'
    })
    .when('/products/new', {
      templateUrl: 'templates/new-product.html',
      controller: 'ProductNewCtrl'
    })
    .when('/products/:id/edit', {
      templateUrl: 'templates/edit-product.html',
      controller: 'ProductEditCtrl'
    })
    .when('/products/:id', {
      templateUrl: 'templates/detail-product.html',
      controller: 'ProductDetailCtrl'
    })    ;
    
    $routeProvider.otherwise({
      redirectTo: '/products',
      templateUrl: 'templates/index.html',
      controller: 'ProductListCtrl'
    });
  }
]);

and services
'use strict';

var app = angular.module('app');

app.factory('Products', ['$resource',function($resource){
  return $resource('/products', {},{
    query: { method: 'GET', isArray: true },
    create: { method: 'POST' }
  })
}]);

app.factory('Product', ['$resource', function($resource){
  return $resource('/products/:id', {}, {
    show: { method: 'GET' },
    update: { method: 'PUT', params: {id: '@id'} },
    delete: { method: 'DELETE', params: {id: '@id'} }
  });
}]);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2015-12-15
@sashasoft

en.stackoverflow.com/a/429516

S
Sergey, 2015-12-08
Protko @Fesor

because controllers in angular are instantiated on each visit to the state or redrawing the view (when an element is removed from the Dom and added.
That is, you can’t catch the problem from the given piece. You need to watch how you use this case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question