The value of a variable remains constant in an Angular controller

I am facing an issue with my HTML page that includes:

<div ng-controller="MyCtrl">
  <div ng-view>Some content</div>

  myVar: {{myVar}}
</div>

Along with an Angular controller:

myModule.controller('MyCtrl', function($scope, $location) {
   $scope.myVar = false;

   $scope.someAction = function() {
     $location.path('/anotherPath');
     $scope.myVar = true; // changes in controller, but not in view
   }
});

The module setup is as follows:

var myModule = angular.module('myModule', ['ngRoute']).config(function ($routeProvider) {

$routeProvider
     .when('/anotherPath', {
       templateUrl: 'anotherPath.html',
       controller: 'MyCtrl'
     })

     .otherwise({
         redirectTo: '/anotherPath.html'
     })
});

anotherPath.html only contains:

<input data-ng-click="someAction()" type="button" class="btn" value="Some action">

Even after clicking on the button and changing the path in the controller, the value of myVar in the view remains false. What could be causing this?

Answer №1

Twice in your code, the controller has been defined: first on the parent div:

<div ng-controller="MyCtrl">

And secondly in the route for /anotherPath:

$routeProvider
     .when('/anotherPath', {
       templateUrl: 'anotherPath.html',
       controller: 'MyCtrl' <-- This will be assigned to <div ng-view>
     })

This results in:

<div ng-controller="MyCtrl">
    <div ng-view ng-controller="MyCtrl">
    </div>
</div>

So when you invoke $scope.someAction(), it references the function from the inner view's controller rather than the parent controller.

To resolve this, assign a unique controller to your View in the route definition:

Angular:

$routeProvider
     .when('/anotherPath', {
       templateUrl: 'anotherPath.html',
       controller: function($scope) {
           // Implementation is optional here
       }
     })

HTML:

<div ng-controller="MyCtrl">
  <div ng-view>Some content</div>

  myVar: {{myVar}}
</div>

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

Troubleshooting unexpected issues with dynamically updating HTML using innerHTML

Need help with a renderWorkoutUpdated function that replaces specific workout records with updated values. _renderWorkoutUpdated(currentWorkout) { let html = `<li class="workout workout--${currentWorkout.type}" data-id="${ curre ...

What is the technique for arranging the display of a component in React?

Is there a way to dynamically render a component in my react-app at a specific date and time, like 6.00PM on October 27, 2022? I want to release a form for signing up starting from that exact moment. The timestamp information will be stored in my database ...

The value returned by $(this).next() is undefined

I'm struggling to implement jQuery functionality to toggle the display of a div, but I am encountering an issue where my jQuery code is unable to select it. Every time I try, it returns undefined. Can anyone provide assistance? $(document).on(&apos ...

Is there a way to stop bootstrap popover overflow from spilling out of its container?

I'm currently using Bootstrap's popover feature, but I'm struggling to prevent the popover from overflowing its container. Any suggestions on how to achieve this? Check out the demo on Plunker <!DOCTYPE html> <html> <head&g ...

Transfer the output to the second `then` callback of a $q promise

Here is a straightforward code snippet for you to consider: function colorPromise() { return $q.when({data:['blue', 'green']}) } function getColors() { return colorPromise().then(function(res) { console.log('getColors&ap ...

What is the best way to retrieve the HTML output generated by AngularJS?

Is there a way to access the rendered HTML content inside a div and place it within the controller's scope in Angular? I am still learning about directives in Angular but I'm having trouble retrieving the rendered HTML after it is displayed. Any ...

Having trouble getting Angular's ng-repeat to work properly after making a $http.post

For a while now, I have been trying to address an issue I'm facing. The problem arises after fetching data through the post method, where my HTML content fails to update accordingly. My website pages are being altered by utilizing $routeProvider, with ...

Challenges in establishing the initial connection between Express.js and MongoDB

Having spent a significant amount of time researching how to set up MongoDb in an Express/NodeJs application, I believed I had a good understanding of how to implement it efficiently. I decided to initialize my mongodbConnection in the WWW file provided by ...

Deciphering HTML with AngularJS

We are currently working with AngularJS version 1.5.6 and facing an issue with HTML characters not being displayed correctly in our text. Despite trying various solutions, we have been unsuccessful in resolving this issue. We have explored numerous discuss ...

Restricting Entry to a NodeJS Express Route

Currently, I am in the process of developing an express project where I have set up routes to supply data to frontend controllers via ajax calls, specifically those that start with /get_data. One issue I am facing is how to secure these routes from unauth ...

In the absence of an Avatar, verify the gender from the JSON data and insert it into the image

I have created my very first app where users can upload their avatars and set their gender. If a user (in this case, a girl) does not upload an avatar, I want to check the JSON data for their gender information. Based on this gender information, I want to ...

What is the method for retrieving the XMLHttpRequest errors registered with addEventListener?

I am struggling to find a solution. https://i.stack.imgur.com/bRJho.gif ...

The chosen options are not appearing. Could this be a problem related to AngularJS?

I am working on setting up a dropdown menu in HTML that includes only the AngularJS tag. This dropdown menu will be used to populate another AngularJS dropdown menu. Below is the code for the first dropdown menu: <select class="form-control" ng-model=" ...

The dollar sign is not available during the onload event

Can someone help me with the error I am encountering where $ is unidentified when using onload on my page? This is a simple sample page created to call a function after the page has loaded. Jquery Code $(document).ready(function(){ alert("loaded"); }) ...

Search through a JSON object, identify all keys that start with the same letter, and transfer them to a new JSON data structure

I am looking to iterate through my JSON data and extract all keys along with their values that start with the letters "QM". Below is an example of my JSON content: [ { MHF46: 'Ledig', MHF181: '06', QM6_QMSI2: '1899-12-30 ...

The error you are seeing is a result of your application code and not generated by Cypress

I attempted to test the following simple code snippet: type Website = string; it('loads examples', () => { const website: Website = 'https://www.ebay.com/'; cy.visit(website); cy.get('input[type="text"]').type(& ...

"Incorporating HTML elements within an ng-repeat directive

I have a list that I created using ng-repeat <li ng-repeat="item in items">{{item}}</li> All of my items are text except for one that is meant to be an image. However, the HTML of the image tag is not rendering properly and is being display ...

Can the console logs be disabled in "Fast Refresh" in NextJS?

When I'm running multiple tests, my browser's console gets cluttered with messages every time a file is saved. Is there a way to disable this feature? For example: [Fast Refresh] completed in 93ms hot-dev-client.js?1600:159 [Fast Refresh] rebuil ...

Having trouble authenticating SPA using passport-azure-ad's Bear Strategy

While I was trying to integrate Azure AD into an AngularJS single page app, I encountered some difficulties getting this tutorial to work. You can find the tutorial here. The tutorial is based on the Azure AD v2.0 endpoint, but unfortunately my organizati ...

I am struggling to add a list from these nested functions in Express, but for some reason, the items are not being properly

I am currently working with three nested functions and facing an issue where the last function is not returning the desired list of items. Interestingly, when I log the results of the last function within the loop, I can see the URLs that I need. However, ...