Reputation: 2295
I have a directive that displays buttons. Quick example:
<my-directive></my-directive>
Inside the directive is HTML similar to the following. (this will display two buttons once the page is rendered).
<button ng-repeat="option in options">{{option}}</button>
Here is a more detailed look at the directive I mentioned before:
<my-directive ng-model="someModel" options="[0, 1]" ui-options="['Cat', 'Dog']>
</my-directive>
>>> Result: 2 html buttons.
Main Question: I would like to disable the Dog
button if a certain condition is met.
I've tried conditionally adding a disabled
directive to the directive if the condition is met, but that disables BOTH the Cat
and Dog
buttons, like so: (on the directive element)
ng-attr-disabled="dogIsbad()"
of course, that disables both buttons because the attribute is on the directive. How can I only add the disabled attribute to the Dog
button without modifying the actual directive?
Upvotes: 0
Views: 82
Reputation: 13488
angular.module('app', [])
.controller('ctrl', ['$scope', function($scope) {
$scope.options = ['cat', 'dog'];
$scope.dogIsbad = function(option){
return option == 'dog';
}
}])
.directive('myDirective', function() {
return {
scope: {
options: '=',
dogIsbad: '&'
},
template: '<button ng-disabled="dogIsbad({option: option})" ng-repeat="option in options">{{option}}</button>'
};
});
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<div ng-app='app' ng-controller="ctrl">
<my-directive options="options" dog-isbad='dogIsbad(option)'></my-directive>
</div>
Upvotes: 1
Reputation: 75
you could pass the option as a paramater to dogIsbad() and check if the option is dog.
<button ng-repeat="option in options" ng-disabled="dogIsbad(option)">{{option}}</button>
In controller
dogIsbad = function(option){ return (option == "Dog");}
Upvotes: 1
Reputation: 574
You have to pass it in the options like
<my-directive
ng-model="someModel"
options="[0, 1]"
ui-options="[{'name': 'Cat', disabled: true}, {name: 'Dog', disabled: false}]>
</my-directive>
And then use it in the button display
<button ng-repeat="option in options" ng-disabled="option.disabled">{{option.name}}</button>
Upvotes: 1