Angular Controller As Syntax-no method'$ watchCollection'

dma*_*man 3 angularjs angularjs-scope

我试图在Angular中将Controller作为语法.在这一点上,我在我的routerProvider中有它...不确定它对我遇到的问题是否重要,但在这里它仍然是:

 angular.module('ucp.kick', [
  'ngRoute'
])
.config ($routeProvider, APP_BASE_URL) ->
  $routeProvider
  .when APP_BASE_URL + 'kicks',
    name: 'Kicks'
    templateUrl: 'kick/partials/kick.html'
    controller: 'kick as KickController'
Run Code Online (Sandbox Code Playgroud)

这是我的控制器的浓缩版本:

  this.$watchCollection('filtered.devices', function(devices) {
    return this.filteredDevices = devices;
  });
Run Code Online (Sandbox Code Playgroud)

但我得到:

TypeError: Object [object Object] has no method '$watchCollection'
Run Code Online (Sandbox Code Playgroud)

我意识到当使用控制器作为语法时,您不希望注入范围.那么,我该如何访问$watchCollection功能呢?

dav*_*ave 5

你仍然需要注射$scope才能使用$watch$watchCollection.现在,你会认为你可以这样做:

$scope.$watchCollection('filtered.devices', function (newVal, oldVal) {});
Run Code Online (Sandbox Code Playgroud)

要么

$scope.$watchCollection('this.filtered.devices', function (newVal, oldVal) {});
Run Code Online (Sandbox Code Playgroud)

但那不行.所以你需要做:

var that = this;
$scope.$watchCollection(function () {
    return that.filtered.devices;
}, function (newVal, oldVal) {

});
Run Code Online (Sandbox Code Playgroud)

要么:

$scope.$watchCollection(angular.bind(this, function () {
    return this.filtered.devices;
}), function (newVal, oldVal) {

});
Run Code Online (Sandbox Code Playgroud)

要么:

$scope.$watchCollection("KickController.filtered.devices", function(newVal, oldVal) { });
Run Code Online (Sandbox Code Playgroud)