0

I'm trying to implement an AngularJS directive that takes attribute-flag selected, which indicates initial state + any current value, if it is assignable.

How can I implement a verification in AngularJS directive to see that the attribute is assignable, before setting a value in it?

app.directive('customControl', [function () {
    return {
        restrict: 'E',
        scope: {
            selected: '=?', // optional, initial + current selected state;
        },
        templateUrl: 'views/directives/customControl.html',
        link: function (scope, elem, attr) {
            if (/* scope.selected is assignable */) {
                scope.selected = /* some value */;
            }
        }
    };
}]);

1 Answer 1

1

You could use the $parse service for that:

link: function(scope){
    var selectedGet = $parse(attrs.selected);
    var selectedSet = selectedGet.assign;

    // etc...

    if (selectedSet){
      selectedSet(scope.$parent, obj);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I have tried using try/catch, it didn't work, the exception still propagates outside the catch block.
@vitaly-t, yeah, you're right - it wouldn't catch it... I'll remove it
Why use selectedSet(scope, obj) instead of scope.selected = value? I have tried the latter first, and it worked.
@vitaly-t, either way would work in your case, but the former approach works even if you didn't have an isolate scope. Actually, it should be scope.$parent

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.