Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Controller As Syntax-no method '$watchCollection'

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;
  });

But I get:

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

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

like image 861
dman Avatar asked Aug 31 '26 17:08

dman


2 Answers

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) {});

or

$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) {

});

or:

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

});

or:

$scope.$watchCollection("KickController.filtered.devices", function(newVal, oldVal) { });
like image 182
dave Avatar answered Sep 04 '26 01:09

dave


controller as does not replace the controller with $scope. Controllers don't have a $watchCollection property. You still have to inject $scope and use $scope.$watchCollection and you have to use the controller identifier as the name of the collection to watch

$scope.$watchCollection("KickController.filtered.devices"

That being said, using $watch and $watchCollection can usually be avoided and you can just work with the data bindings. Angular will use $watchCollection internally on the collection. Specifically I'm not sure that you need this other property filteredDevices when you can just use a filter explicitly on the existing collection.

like image 27
Explosion Pills Avatar answered Sep 04 '26 02:09

Explosion Pills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!