Every time the attribute of the Angular controller changes, it is reinitialized

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;
  }
})();

Answer №1

The issue resided in how I declared my directive:

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

As a result, a new controller was being initialized for each post on the page.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using the .each method in AJAX JQUERY to iterate through callback JSON data and applying an if statement with Regular Expression to identify matches

Implementing a live search feature using ajax and jQuery involves running a PHP script that returns an array of database rows, encoded with JSON, based on the textfield input. This array is then iterated through in JavaScript after the callback function. ...

Navigating through integration challenges between Angular UI Calendar and Google Calendar v3 API

Currently, I am in the process of integrating the Angular UI Calendar into my project using the Google Calendar API. I have successfully implemented it with the v3 Calendar API using the jQuery plugin version through FullCalendar on its own. However, I am ...

endless cycle of scrolling for div tags

My goal is to incorporate a tweet scroller on I believe it uses the tweet-scroller from Unfortunately, this link seems broken as the demo is not functioning. I searched for an alternative solution and came across http://jsfiddle.net/doktormolle/4c5tt/ ...

What is the best way to handle a single promise from a shared listener?

I am working on implementing an event listener that will receive events from a server whenever a specific task is completed. I want to structure each task as a promise to create a more organized and clean workflow. How can I resolve each task promise by i ...

Previewing multiple images before uploading them using jQuery

Currently, I am utilizing the following code for my image uploader: HTML: <input type="file" id="files" name="files[]" multiple /> <ul id="list"></ul> JavaScript: function handleFileSelect(evt) { var files = evt.target.files; // FileL ...

Whenever I am building a React application, I encounter a bug that states: "node:fs:1380 const result = binding.mkdir()"

Whenever I try to enter the command: create-react-app my-app --template typescript I keep encountering this error message: node:fs:1380 const result = binding.mkdir( ^ Error: EPERM: operation not permitted, mkdir 'D:\ ...

data-cy appears in the DOM structure, yet remains unseen

I'm seeking some clarity on how to effectively use Cypress. While writing end-to-end tests, I encountered a failed test due to the element not being visible. A helpful answer I found assisted me in resolving this issue by clicking an element that was ...

Guide on executing a jar file using JavaScript and obtaining a JSON output

Is there a way to execute and capture the output of a jar file that returns a json using javascript? ...

The occurrence of an unanticipated character '#' was found

I'm currently facing an issue while using webpack to load dependencies. Whenever I execute the npm run dev command, I encounter the following error: Uncaught Error: Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: ...

How to rename a class of an image tag using jQuery

I need to update the class name in my image tag <img src="img/nex2.jpeg" class="name"> When hovering over with jquery, I want to add a new class to it. After hovering, the tag should appear as follows: <img src="img/nex2.jpeg" class="name seco ...

Creating an If statement to evaluate the state of a parameter

In my simple Graphics User Interface, when the user clicks on "move", a yellow rectangle div moves across the screen. Now, I am trying to implement an event based on the position of the rectangle on the page. For example, if the div is at 400px (right), t ...

Retrieve a file using the Google Drive API through PHP Slim API

I've created a PHP Slim API Webservice that accesses my Google Drive Files and sends them to my Angular Frontend. I'm unsure of the best way to download files from Google Drive. 1. Can I directly download a file to my Browser using GuzzleHTTP st ...

Pass the object either in JSON format or as a variable using the drag and drop feature

Here's a quick question: when using the Drag and Drop system, I'm not sure which method is better. Is it more efficient to : utilize setData and getData to transfer a JavaScript object? (Utilizing JSON conversion since setData only passes st ...

How can you eliminate the first elements of two or more arrays of objects until all of their first elements match based on a specific field?

My Typescript code includes a Map object called `stat_map` defined as const stat_map: Map<string, IMonthlyStat[]> = new Map(); The interface IMonthlyStat is structured as shown below (Note that there are more fields in reality) export interface IMon ...

A tiny blue spot popping up beside the roster of users

I'm working on a render function that displays a list of users with avatars and names. The issue I'm facing is that when the page initially loads, there's a blue dot to the left of each user. However, if I navigate to another page and then g ...

Error in Express.js App: Attempting to access properties of an undefined object (specifically 'transfer-encoding')

Currently, I am developing a blogging app API using express and MongoDB. In my project, I want to include an image for each blog post. However, as someone who is new to express, I encountered a specific issue that has been puzzling me. The error message ...

execute a function upon selecting a radio button

Below is the HTML code that includes two radio buttons. The default checked button is the "lease" option. <input id="quotation_request_payment_option_lease" class="choose_payment_option" name="quotation_request[payment_option]" type ...

Utilizing HTML to call a function and fetching data from AngularJS

I've been struggling to retrieve the value after calling a function in my HTML file. Despite trying various methods after conducting research, I have not achieved success yet. Take a look at the code below: HTML: <div class="form-group"> & ...

Identify the row containing a value of null using jQuery (functionality not performing as anticipated)

Whenever the user clicks on the GetData button, I retrieve JSON data and display it in an HTML table similar to the demo below. Demo: https://plnkr.co/edit/I4XYY6CZohf7IS6wP8dR?p=preview There are instances where the value can be null, such as the loanNu ...

Guide to making a language selection wrapper using a gist script

Currently, I have a Gist file that is written in various languages but all serve the same purpose. As a result, I am interested in developing a language selection feature similar to what is found in the Google docs documentation. https://i.stack.imgur.com ...