问题描述
我试图避免在控制器的功能使用$范围,而不是选择使用
I am trying to avoid using $scope in my controller function, instead opting to use
var viewModel = this;
与控制器视图模型语法。
我的问题是我需要使用NG-变化调用一个函数在我的控制器,但同时我能够从服务访问数据,我无法调用函数。
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();
}
}
})();
控制器被实例化一个指令,它定义了控制器和controllerAs:视图模型
The controller is being instantiated in a directive that defines the controller and controllerAs: 'viewModel'
我的HTML如下:
<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>
我可以打电话给家里的事,当我用的不是引用控制器$范围,但是我觉得这是不理想的。我希望有调用与仍然使用视图模型NG-变化的函数的一种方式。
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.
推荐答案
是正确的。我的控制器不正确接线。问题是,我有另外的控制器在较高的范围这也是设置为controllerAs活跃:视图模型。这引起了我的引用错误的控制器,其中功能并不存在。有一次,我给了该控制器的唯一名称一切顺利这就是为什么它为$范围。
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.
这篇关于在&QUOT AngularJS使用NG-变化;控制器&QUOT;句法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!