0

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.

2
  • Please, update the question with your attempt on using $scope.$watch. For 1.5 and components $onChanges hook is preferable. Commented Nov 28, 2016 at 21:47
  • As I mentioned I have no interest in watching the value for changes. Is there no way to just obtain that value directly from the controller? Commented Nov 29, 2016 at 3:03

1 Answer 1

1

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
   }
},
Sign up to request clarification or add additional context in comments.

2 Comments

turned out to be that it needed to be referenced on this not $scope as in this.vulnerability within the controller Could you change your answer to that and elaborate more on vulnerability="::vulnerability" and ill accept it
Ok. As for one-time bindings, see docs.angularjs.org/guide/expression#one-time-binding . It is a good practice to use them wherever possible, it gives a proper context to the code and does a good job on initial optimization.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.