I'm currently in the process of developing a single page application using angularjs 1 and ngRoute, and I've encountered an issue.
Within a view (/posts) I have a controller (PostsController) with an attribute called 'posts' that holds an array of all posts. Here's a snippet of the 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];
}
}
}
})();
Upon commenting out the test() function, "Hi..." is logged once in the console. However, when uncommented, "Hi..." is logged 1 + vm.posts.length times (7 in this example).
Furthermore, additional function calls also execute 1 + vm.posts.length times which is causing issues.
Any thoughts on what might be causing this and how to resolve it?
Update: After insight from someone, it appears the issue may be related to my templates/routes and it turned out to be correct. Within ng-repeat, I am using a custom directive and removing it results in "Hi..." being displayed only 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;
}
})();