问题
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 ng-change to call a function in my controller but while I am able to access data from a service, I am unable to call functions.
//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 being instantiated in a directive that defines the controller and controllerAs: 'viewModel'
My html looks like this:
<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>
I was able to call things fine when I used $scope instead of referencing the controller however I feel this is not ideal. I was hoping there is a way of calling a function with ng-change that still uses viewModel.
回答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;
function setSimulationPeriod() {
console.log("Entered local setSimulationPeriod");
viewModel.SimulationService.setSimulationPeriod();
}
reorder it like this
function setSimulationPeriod() {
console.log("Entered local setSimulationPeriod");
viewModel.SimulationService.setSimulationPeriod();
}
viewModel.setSimulationPeriod = setSimulationPeriod;
回答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.
来源:https://stackoverflow.com/questions/35143675/using-ng-change-in-angularjs-with-controller-as-syntax