简体   繁体   English

角度:$ scope有效,但“ controller as”不会触发ng-change事件

[英]Angular: $scope works but “controller as” does not fire ng-change event

I have a controller as follows: 我有一个控制器,如下所示:

(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));
        });
    }

  }
})();

Along with an input field (search term): 连同输入字段(搜索词):

<input type="text" class="search-query form-control" placeholder="Search" 
ng-model="controller.searchTerm" ng-change="controller.searchProfiles()"/>

And the start of the profiles.html page is: <div class="container" ng-controller="ProfilesController as controller"> 并且profile.html页面的开始是: <div class="container" ng-controller="ProfilesController as controller">

When using this approach, the change event on the input field does not fire in the controller. 使用这种方法时,输入字段中的change事件不会在控制器中触发。 But changing from 'controller as' style to $scope works fine. 但是从“ controller as”样式更改为$scope可以正常工作。

I'm using the ui-router framework rather than ng-route. 我正在使用ui-router框架而不是ng-route。 (The yeoman generator I used to start chose this for me). (我以前开始使用的yeoman发电机为我选择了这个)。

Question: 题:

I just started angular in the last few days, but read 'controller as' is easier to test. 我最近几天才刚开始使用Angular,但是阅读“ controller as”比较容易测试。 How can I make this work with 'controller as' style? 如何使用“控制器为”样式进行此工作?

According to ng-change . 根据ng-change You should use: 您应该使用:

ng-change="controller.searchProfiles()"

instead of: 代替:

ng-change="controller.searchProfiles"

在定义$scope.$on函数之前,您正在对其进行调用,这将导致其余代码无法加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM