Andrew
Andrew

Reputation: 1013

Get bound object value of angular component from its controller

I have an angular component:

module.exports = {
    bindings: {
        vulnerability: '<',
    },
    controller: ['$scope', function($scope){
       //want to get value of vulnerability from above
       $scope.vulnerability  // doesn't work
    }],
};

which i reference in an ng-repeat

<div ng-repeat="vulnerability in vulnerabilities" class="vulnerability-item">
   <vulnerability-item  vulnerability="vulnerability"> </vulnerability-item>
</div>

The value of vulnerability isn't going to change once the directive is called so I don't need to watch that value, just to reference it once it gets set.

I did put a $scope.$watch on the property just to see if it worked and it did trigger but I couldn't see the new or old value in the handler of the watch so it didn't help me anyway.

I tried $scope.vulnerability and $ctrl.vulnerability which is how I'd reference that property in the directives template but neither worked. How do I get the bound value that is passed in?

adding this watch:

    $scope.$watch('vulnerability', function (oldV, newV) {
        console.log('old', oldV)
        console.log('new', newV)
    })

I get a new undefined and old undefined in the console for each instance of the component although if i change $scope.$watch('vulnerability' to $scope.$watch('nonsense') It still fires the logs once for each component.

Upvotes: 0

Views: 918

Answers (1)

Estus Flask
Estus Flask

Reputation: 222750

If the value isn't supposed to be changed, it should be bound once, vulnerability="::vulnerability". This gives the context to the question (and also saves some time on optimization).

In this case $onInit hook may be used:

...
controller: function() {
   this.$onInit = function () {
     this.vulnerability
   }
},

Upvotes: 1

Related Questions