Sean Lindo
Sean Lindo

Reputation: 1437

Watch for binding changes in an Angular 1.5.3 component?

I have a controller that fetches data to populate a large dropdown:

MySrvc.getData()
    .then(function (response) {
        $scope.someData = response.data;
    });

I also have a component that is instantiated and defined as such..

<my-component foo='someData'></my-component>

angular.module('mod').component('myComponent', {
    bindings: {
        foo: '<'
    },
    controller: function() {

    }
});

ngOptions dictates that you must have an ngModel set as well. I would like the first element of the array to be the selected object. this.selectedElement = this.foo[0]. Problem is, I can't actually write this line of code until I know the binding has been updated.

I can't use scope.$watch in a component and this.$onChanges doesn't seem to be working either. Any ideas?

Upvotes: 0

Views: 530

Answers (3)

Simon Sch&#252;pbach
Simon Sch&#252;pbach

Reputation: 2683

You must have at least angular 1.5.3 to use $onChanges. But then you can use it like that

controller: function() {
     this.$onChanges = function(){
         // your stuff
     }
}

Upvotes: 1

Freezystem
Freezystem

Reputation: 4884

If you want to use a watcher on this.foo you can use $scope.$watch function. It can accept a function as its first argument, so you can watch a particular variable.

try :

$scope.$watch(function () {
  return this.foo;
},true);

Upvotes: 1

byteC0de
byteC0de

Reputation: 5273

you can solve this problem with ng-if

<my-component ng-if="someData" foo='someData'></my-component>

if you add ng-if in your element the directive render after the data has come

Upvotes: 1

Related Questions