我有一个控制器,如下所示:
(function () {
'use strict';
angular
.module('vweb')
.controller('ProfilesController', ProfilesController);
/** @ngInject */
function ProfilesController(profileService, $scope) {
var vm = this;
vm.searchTerm = '';
vm.profileService = profileService;
$scope.$on('$viewContentLoaded',
function () {
vm.searchProfiles();
});
vm.searchProfiles = function() {
alert("term: " + vm.searchTerm);
profileService.searchProfiles(vm.searchTerm)
.then(function (profiles) {
alert("Here's my profiles " + angular.toJson(profiles));
});
}
}
})();
连同输入字段(搜索项):
<input type="text" class="search-query form-control" placeholder="Search"
ng-model="controller.searchTerm" ng-change="controller.searchProfiles()"/>
profiles.html页面的开头是:<div class="container" ng-controller="ProfilesController as controller">
使用此方法时,输入字段上的更改事件不会在控制器中触发。但从"controller as"样式更改为$scope
效果良好。
我使用的是ui路由器框架,而不是ng路由。(我以前启动的yeoman发电机为我选择了这个)。
问题:
最近几天我刚开始使用angular,但读"controller as"更容易测试。如何使用"controller as"样式使其工作?
在定义$scope.$on
函数之前,您正在调用该函数中的searchProfiles,这导致其余代码无法加载。
根据ng-change
。您应该使用:
ng-change="controller.searchProfiles()"
而不是:
ng-change="controller.searchProfiles"