Angular Controller As syntax - no method '$ watchCollection'
I am trying to do Controller As Syntax in Angular. At the moment I have this in my routerProvider ... not sure if it matters for the problem I am having, but here it is anyway:
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;
});
But I am getting:
TypeError: Object [object Object] has no method '$watchCollection'
I understand that when using a controller as your syntax, you don't want to inject a scope. So how do I access the function $watchCollection
?
source to share
You still need to enter $scope
in order to use $watch
and $watchCollection
. Now, you might be thinking what you can do:
$scope.$watchCollection('filtered.devices', function (newVal, oldVal) {});
or
$scope.$watchCollection('this.filtered.devices', function (newVal, oldVal) {});
But that won't work. Therefore, you need to either do:
var that = this;
$scope.$watchCollection(function () {
return that.filtered.devices;
}, function (newVal, oldVal) {
});
or
$scope.$watchCollection(angular.bind(this, function () {
return this.filtered.devices;
}), function (newVal, oldVal) {
});
or
$scope.$watchCollection("KickController.filtered.devices", function(newVal, oldVal) { });
source to share
For a watch, you still need to use $scope
.
After typing $scope
into your controller, just like before the syntax appears controllerAs
, you can do:$scope.$watchCollection(..)
To keep repeating what I mean: if the value you are trying to look at is bound to a value using syntax controllerAs
for example kickController.someValue
, then you will see that value$scope.$watchCollection('kickController.someValue',...)
Sidenote: Showing all your code will help because it looks like you can define your controller definition backwards. You meant:
...
controller: KickController as kick
and then:
var kick = this;
?
source to share
controller as
does not replace the controller $scope
. Controllers have no property $watchCollection
. You will still have to inject $scope
and use $scope.$watchCollection
and you have to use the controller id as the name of the collection to view
$scope.$watchCollection("KickController.filtered.devices"
That being said, you can usually avoid using $watch
and $watchCollection
, and you can just work with data bindings. Angular will use $watchCollection
inside a collection. In particular, I'm not sure if you need this other property filteredDevices
when you can just use the filter explicitly on an existing collection.
source to share