Skip to content Skip to sidebar Skip to footer

Using Ng-change In Angularjs With "controller As" Syntax

I am trying to avoid using $scope in my controller function, instead opting to use var viewModel = this; with 'controller as' viewModel syntax. My problem is that I need to use n

Solution 1:

angular expressions

You're not calling the function. Instead try:

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

Note the () at the end of your function. Ng-change, like most other angular directives use expressions, meaning they're actually trying to execute a subset of JavaScript. In this case when you just passed a reference to your vm's function, it simply evaluated it rather than executing it.

order of assignment

Also, you've defined the viewModel function before you've defined the function you're setting it to. Move the function declaration above the part of your code where you assign it to your viewModel.

instead of this

viewModel.setSimulationPeriod = setSimulationPeriod;

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

reorder it like this

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

viewModel.setSimulationPeriod = setSimulationPeriod;

Solution 2:

jusopi was right. My controller was not wired up correctly. The problem was that I had another controller active at a higher scope which was also set to controllerAs: viewModel. This caused me to reference the wrong controller where the function did not exist. Once I gave this controller a unique name everything went smoothly which is why it worked for $scope.

Post a Comment for "Using Ng-change In Angularjs With "controller As" Syntax"