简体   繁体   中英

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">

When using this approach, the change event on the input field does not fire in the controller. But changing from 'controller as' style to $scope works fine.

I'm using the ui-router framework rather than ng-route. (The yeoman generator I used to start chose this for me).

Question:

I just started angular in the last few days, but read 'controller as' is easier to test. How can I make this work with 'controller as' style?

According to ng-change . You should use:

ng-change="controller.searchProfiles()"

instead of:

ng-change="controller.searchProfiles"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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