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

Is there a built-in method in Next.js 13 to secure routes from unauthorized access?

In my project, I have the following pages: /about, /user, and /user/[id]. Unfortunately, I am unable to access req.page, which provides the slug (i.e. /user/[id]), making it difficult for me to implement logic to redirect requests from unauthenticated user ...

Using Chart.js to display JSON data in a graphical format

I am facing an issue and need some help. I have gone through various tutorials and questions, but none of them seem to address my specific problem. When making an ajax request to my PHP file, I receive a JSON response like this (as seen in the console log) ...

What sets Angular.js apart from Angular.dart?

Although I have some knowledge of Angular.js, I am now interested in learning Dart and Angular.dart on my own. I am curious to understand the nuances and variances between these two technologies. Despite the fact that the Angular.dart tutorial explicitly ...

Is there a way to handle button click event when utilizing this.props.children in React?

I have recently completed a React component that serves as a modal wrapper. The content for this modal is passed through the props.children property. Inside the content, there is a button that, when clicked, should trigger an event in the parent component. ...

ng-model does not function properly with ng-repeat in a dropdown menu

I am trying to display images in an option list using ng-repeat because I couldn't achieve it with ng-options. However, I am facing an issue where I am unable to retrieve the selected value from ng-change. It seems like ng-model is not working as expe ...

nextAuth.js is failing to access the accessToken, returning only the values {iat, exp, jti} instead

Here is the code I am working with: import NextAuth from "next-auth" import CredentialsProvider from "next-auth/providers/credentials" export default NextAuth({ sectret:process.env.NEXTAUTH_SECRET, session: { strategy: "jw ...

Should I use Mongoose schema methods or prototype functions?

I am curious about the functionality of functions and ES6 classes in relation to new objects created from a mongoose schema. I wonder if the functions are duplicated for each new object and what the best approach is when utilizing ES6 classes. To illustrat ...

Updating a query parameter with jQuery

Looking for a way to modify the value of a query parameter in a URL using jQuery. There are two example URLs: www.domain.com/?id=10&name=xxx and www.domain.com/?name=xxx&id=10 I want to update the id parameter to something like www.domain.com/ ...

Encountering a 'Cannot Get /' Error while attempting to reach the /about pathway

I attempted to create a new route for my educational website, and it works when the route is set as '/', but when I try to link to the 'about' page, it displays an error saying 'Cannot Get /about' Here is the code from app.js ...

The issue persists with the event listener not responding to input key

Can the Keycode that is pressed during the firing of addEventListener input be retrieved? <p contentEditable="true" id="newTask">New task</p> document.getElementById("newTask").addEventListener("input" ...

Utilize ng-bootstrap in an Angular CLI project by integrating it with npm commands

I've been attempting to set up a project using Angular CLI with ng-bootstrap, but I'm having trouble getting the style to work properly. Here are the exact steps I followed (as outlined in the get-started page): Create a new project using `ng n ...

Achieving Efficiency with Handlebars: Streamlining Remote Template Organization and

I am looking for a way to better organize my HB template by splitting it into different HTML files. In this case, I have created a file called helpers.html. This file contains two script tags: <script id='alert' type='text/template>... ...

tips for choosing tags that are nested within specific parent tags

I'm looking to locate and count all the <"a"> tags within every <"code"> tag on a given webpage using JavaScript. How can I accomplish this? I attempted methods like document.getElementsByTagName("code").getElementsByTagName("a"); and document. ...

Looking for a solution to eliminate Parsing Error: Unexpected Token when developing with React? I've already implemented ESLint and Prettier

Currently, I am working on building a form in React with MUI. Below is the code snippet that I have been working with: const textFields = [ { label: 'Name', placeholder: 'Enter a company name', }, { label: 'Addres ...

Location of Ajax callback function

I encountered an issue with a callback function that was placed within $(document).ready. The callback function wasn't functioning as expected. Surprisingly, when I moved it outside of $(document).ready, the code started working flawlessly. I am puzzl ...

Maintain the current states when returning to a previous point in time

In my Angular app, I have multiple pages that allow users to make changes such as opening tabs and pills, modals, etc. For instance, if a user opens a modal and then clicks a link within that modal that takes them to another page, I want the original page ...

Invoking a JavaScript function within a different JavaScript function

Is there a way to ensure that the JavaScript function works properly even when using a text editor? var editor = $('#CKEditor1').ckeditorGet(); editor.on("instanceReady", function () { this.document.on("keydown", function (event) { ...

What is the best way to cancel a Promise if it hasn't been resolved yet

Let's consider a situation where I have implemented a search function to make an HTTP call. Each call made can have varying durations, and it is crucial for the system to cancel any previous HTTP requests and only await results from the latest call. ...

Getting the values of $scope variables from AngularJS in the controller to the view

I have a simple scope variable on my AngularJS Controller. It is assigned a specific endpoint value like this: $scope.isItAvailable = endpoint.IS_IT_AVAILABLE; How can I properly use it in my view (HTML) to conditionally show or hide an element using ng- ...

What is the method for retrieving an attribute's value from an object that does not have key-value pairs?

My current project involves working with dynamoose and running a query that produces the following output: [ Document { cost: 100 }, lastKey: undefined, count: 1, queriedCount: undefined, timesQueried: 1 ] When I use typeof(output), it returns O ...