Reputation: 855
I want my input to be required based on condition.
<input type="text" custom-directive ng-required="isRequired" />
I have defined property isRequired as boolean false. Required functionality works fine according to the isRequired property. But inside the custom directive i am getting $attrs.required as true for all scenarios.
module.directive('customDirective', function () {
var link = function ($scope, $el, $attrs, $controllers) {
$scope.required = $attrs.required;
}
return {
restrict: 'A',
link: link
};
});
Thanks
Upvotes: 1
Views: 2273
Reputation: 4880
I am unable to explain why $scope.required
would be true in this case (perhaps you are setting it to true
somewhere else and should be using a child or isolation scope?)... I would expect it to be undefined
based on what you have provided. The other possibility is that you have multiple elements with this directive in the same scope and one of them is setting that value to true for all of them.
By replacing your $scope.required = $attrs.required;
line with
$attrs.$observe('required', function(value) {
$scope.required = value;
});
it should properly pick up the value of the required
attribute (and when it changes!).
If you have that directive being applied to multiple elements in the same scope you should use a child scope. All you need to do is add scope: true
to the object returned by your directive.
If this does not work, please post more of your application's code.
Upvotes: 3