我正在尝试在Angular中执行Controller As Syntax。在这一点上,我将它放在我的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'
这是我的控制器的精简版:
this.$watchCollection('filtered.devices', function(devices) {
return this.filteredDevices = devices;
});
但是我得到:
TypeError: Object [object Object] has no method '$watchCollection'
我意识到当使用控制器作为语法时,您不想注入作用域。那么,如何访问
$watchCollection
函数? 最佳答案
您仍然需要注入$scope
才能使用$watch
和$watchCollection
。现在,您认为您可以:
$scope.$watchCollection('filtered.devices', function (newVal, oldVal) {});
要么
$scope.$watchCollection('this.filtered.devices', function (newVal, oldVal) {});
但这行不通。因此,您需要执行以下任一操作:
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) { });