Guillaume Docquier
Guillaume Docquier

Reputation: 23

Angular controller initialized every time its attribute changes

I am building a one page application using angularjs 1 with ngRoute and I've come across a problem.

I have a view (/posts) using a controller (PostsController) that has an attribute called 'posts' which is an array containing all posts. Here's some code:

(function(){
  angular
    .module('thingy.posts.controllers')
    .controller('PostsController', PostsController);

  PostsController.$inject = ['$scope'];

  function PostsController($scope) {
    var vm = this;

    vm.posts = [];

    activate();

    function activate() {
      console.log("Hi...");

      test();

      // Simulates loading all posts from db
      function test() {
        vm.posts = [1,2,3,4,5,6];
      }
    }
  }
})();

Now if I comment test(), "Hi..." is printed once in the console. However, when I uncomment it, "Hi..." is printed 1 + vm.posts.length times (7 in this example).

Moreover, subsequent function calls also execute 1 + vm.posts.length times which is problematic.

Any ideas on what is causing this and how I can fix it?

Edit: Someone suggested the error might lie in my templates/routes and he was right. I am using a custom directive inside ng-repeat and when I remove it "Hi..." only appear once.

posts-index.html:

<div ng-repeat='post in vm.posts'>
    <post post="post"></post>
</div>

Post.directive.js:

(function () {
  'use strict';

  angular
    .module('thingy.posts.directives')
    .directive('post', post);

  function post() {
    var directive = {
      controller: 'PostsController',
      controllerAs: 'vm',
      restrict: 'E',
      scope: {
        post: '='
      },
      templateUrl: '/static/templates/posts/post.html'
    };

    return directive;
  }
})();

Upvotes: 0

Views: 50

Answers (1)

Guillaume Docquier
Guillaume Docquier

Reputation: 23

The problem lied in my directive declaration:

var directive = {
      controller: 'PostsController',
      controllerAs: 'vm',

This was initializing a controller for every post on my page.

Upvotes: 0

Related Questions