Angular Controller As Syntax-no method '$watchCollection' [英] Angular Controller As Syntax-no method '$watchCollection'

查看:19
本文介绍了Angular Controller As Syntax-no method '$watchCollection'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Angular 中使用 Controller As Syntax.在这一点上,我在我的 routerProvider 中有它......不确定这对我遇到的问题是否重要,但无论如何:

I am trying to do Controller As Syntax in Angular. At this point, I have it in my routerProvider...not sure if it would matter for the issue I am having, but here it is anyways:

 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'

这是我的控制器的精简版:

Here is a condensed version of my controller I have:

  this.$watchCollection('filtered.devices', function(devices) {
    return this.filteredDevices = devices;
  });

但我明白了:

TypeError: Object [object Object] has no method '$watchCollection'

我意识到当使用控制器作为语法时,你不想注入作用域.那么,如何访问 $watchCollection 函数?

I realize when using the controller as syntax, you do not want inject the scope. So, how do I access $watchCollection function?

推荐答案

你仍然需要注入 $scope 才能使用 $watch$观看集合.现在,您会认为您可以这样做:

You will still need to inject $scope in order to use $watch and $watchCollection. Now, you would think you could do:

$scope.$watchCollection('filtered.devices', function (newVal, oldVal) {});

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

但这行不通.所以你需要做:

But that won't work. So you need to either do:

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

});

或:

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

});

或:

$scope.$watchCollection("KickController.filtered.devices", function(newVal, oldVal) { });

这篇关于Angular Controller As Syntax-no method '$watchCollection'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆