Leveraging ng-change in AngularJS when utilizing the "Controller As" syntax

Attempting to steer clear of using $scope within my controller function, I have instead chosen to use

var viewModel = this;

employing the "controller as" viewModel syntax. The issue at hand is that while I can access data from a service, invoking functions seems to be problematic.

//Controller
(function () {
'use strict';

angular
    .module('app')
    .controller('GeneralSettingsController', GeneralSettingsController);

GeneralSettingsController.$inject = ['SimulationService'];
function GeneralSettingsController(SimulationService) {
    var viewModel = this;
    
    viewModel.SimulationService = SimulationService;
    viewModel.setSimulationPeriod = setSimulationPeriod;

    function setSimulationPeriod() {
        console.log("Entered local setSimulationPeriod");
        
        viewModel.SimulationService.setSimulationPeriod();
    }
}
})();

The controller is initialized in a directive specifying the controller and controllerAs: 'viewModel'

This is how my HTML code looks:

<div class="col-xs-2">
    <input type="text" class="form-control" id="startyear" name="startyear" placeholder="start year"
                       autocomplete="off" value="2017" maxlength="4"
                       ng-model="viewModel.SimulationService.data.simulationPeriodStart" ng-change="viewModel.setSimulationPeriod">
</div>

Prior to referencing the controller, calling functions was seamless by utilizing $scope. However, I believe there could be a better way to achieve this without reverting back to $scope. Is it possible to still call a function with ng-change while using viewModel?

Answer №1

Working with Angular Expressions

Make sure to call the function correctly. Adjust your code like this:

<input ng-change="viewModel.setSimulationPeriod()">

Ensure that you include () at the end of your function. Angular directives, including ng-change, use expressions which are essentially a subset of JavaScript code. When you merely reference your vm's function without invoking it, it only evaluates it without executing.

Correct Order of Assignments

Another thing to consider is the sequence in which you declare and assign functions. Be sure to define the function before assigning it to viewModel.

Instead of:

viewModel.setSimulationPeriod = setSimulationPeriod;

function setSimulationPeriod() {
    console.log("Entered local setSimulationPeriod");
    viewModel.SimulationService.setSimulationPeriod();
}

Reorder like this:

function setSimulationPeriod() {
    console.log("Entered local setSimulationPeriod");
    viewModel.SimulationService.setSimulationPeriod();
}

viewModel.setSimulationPeriod = setSimulationPeriod;

Answer №2

jusopi provided the solution I needed. It turns out my controller was not properly configured. The issue stemmed from having another controller active at a higher level with the same alias "viewModel". This led me to access the wrong controller where the required function did not exist. Renaming the controller resolved the problem and everything worked smoothly, hence why it functioned correctly for $scope.

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

Exploring object key-value pairs using the 'for in' loop in JavaScript

Embarking on a project to develop a quiz in javascript, I am starting with an array that holds the questions as anonymous objects. var allQuestions = [{ "question": "Who was Luke's wingman in the battle at Hoth?", "choices": ["Dak", "Biggs", "Wedge", ...

AngularJS in combination with moments.js is producing inaccurate dates

Using AngularJS, I am trying to parse a string into a date. My current code is as follows: var d = moment.utc("2011-10-02T22:00:00.000Z", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); var year = d.year(); var month = d.mont ...

Utilizing an npm Package in Laravel - Dealing with ReferenceError

I'm having trouble with the installation and usage of a JS package through npm. The package can be found at . First, I executed the npm command: npm install --save zenorocha/clipboardjs Next, I added the following line to my app.js file: require(& ...

Is it possible for the Chrome mobile camera to take up the full screen size on

Currently, I am using the code below to access the camera and display the stream. The width of the element is 100%, but the height seems to be around 70%. Is there a better way to make it fill the entire screen? HTML <video autoplay class="screen"> ...

What is the best way to transform React API data into props that can be utilized in different components?

I've been struggling with this issue for quite some time now, unable to understand how to manipulate the data in a way that allows me to use it in other components. Although I can display the data correctly, I'm advised to structure it within a f ...

Storing socket.io data in an array

Having trouble getting the desired array of arrays from my socket.io emitter. The structure I need is: [ [{...},{...},{...}] , [{...},{...}] , [{...}] ] But instead, I am receiving a different format. https://i.stack.imgur.com/3PY0u.jpg I require all t ...

Jquery double-click Event Not Functioning Properly

I've been attempting to toggle the visibility of my footer navbar while also changing the chevron icon. When the navbar is hidden, I want the chevron pointing up to be displayed, and when the navbar is shown, I want the chevron pointing down to be dis ...

The TypeScript factory class anticipates an intersection

In my code, I have a class factory called pickSomething that generates a specific type based on a key provided from a ClassMap: class A { keya = "a" as const; } class B { keyb = "b" as const; } type ClassMap = { a: A b: B } c ...

http.get is ineffective when utilized within a for loop to retrieve data from mongo through express

I am currently facing an issue with fetching data from MongoDB using Express to Angular within a for loop. Despite being able to access the data inside the GET instance, I'm struggling to do so outside of it. Below is a snippet of my code: var daily_ ...

Is there a way for me to gain access to alter the price function within Magento?

Now, I am faced with the task of customizing the discounted price for my Shopping cart. After some independent research, I discovered that by modifying the view.phtml and item.phtml files, I can properly display the desired price. However, I still feel uns ...

What is the best way to link labels with input fields located separately in Angular?

Imagine a scenario where labels and form fields are being created in a *ngFor loop, as shown below: app.component.ts export class AppComponent { items = ['aaa', 'bbbbbb', 'ccccccccc'] } app.component.html <div class ...

What is the best way to handle an ajax call while working with the main Vue instance?

I have a VueJS component that makes an AJAX call to GitHub using the following code: (Child) Component Vue.http.get('user/repos').then((response) => { console.log(response); }, (response) => { console.log(response); }); The issue ...

Filtering properties of objects in Vue

I am currently dealing with an array of objects that represent continents: data() { return { continents: [ { name: "South America", countries: [ { name: "P ...

Is it possible to meta-refresh a page for redirection?

When creating a webpage, I included a META tag like this: <META http-equiv="refresh" content="5;URL=http://www.google.com"> The issue is that mobile browsers do not support this meta tag. It redirects properly on web browsers, but not on mobile dev ...

The promise catch method does not handle JSON parsing correctly

Utilizing Angular's Http to interact with my API has been successful for handling responses with a status of 200. The data is parsed correctly and outputted as expected within the first .then() block. However, when encountering an error with a status ...

Dealing with Database Timeout in Express JS

I have been trying to extract SQL query execution into a separate file to prevent code repetition, but I am facing timeout issues during execution. var mysql = require('mysql'); const connectionData = { host: 'localhost', user: ...

Troubleshooting Cross-Origin Resource Sharing problem with Stripe API integration in Angular

I am diving into the world of Stripe API and CORS for the first time. I've set up a POST request from Angular to my Node.js server. Since the client origin differs from the server destination, I have implemented CORS on the server side. When inspectin ...

Encountering an unforeseen issue with the config.kit.methodOverride while executing Svelte

While working on a Svelte project, I recently updated it to the latest version using the migration tools provided. However, now the project doesn't seem to interact with npm as expected. When I run npm i, it installs the node modules but throws an er ...

Update a BehaviourSubject's value using an Observable

Exploring options for improving this code: This is currently how I handle the observable data: this.observable$.pipe(take(1)).subscribe((observableValue) => { this.behaviourSubject$.next(observableValue); }); When I say improve, I mean finding a wa ...

Get a webpage that generates a POST parameter through JavaScript and save it onto your device

After extensive research, I have hit a roadblock and desperately need help. My task involves downloading an HTML page by filling out a form with various data and submitting it to save the responses. Using Firebug, I can see that my data is sent over POST, ...