I am building a custom element directing in AngularJS. My element will be used like this:
<my-element my-attribute="false"></my-element>
If the user does NOT set my-attribute
, I want it to default to true
. How do I give the directive attribute a default value? Currently, I have the following:
myApp.directive('myElement', function ($window) {
return {
restrict:'E',
transclude: true,
scope: {
myAttribute: '='
},
controller: function($scope) {
},
template: '<div>Hello <span ng-if="myAttribute == true">, World</span></div>'
};
});
Thank you!
First, be sure to make the attribute optional. With your current code, if your directive is used like that…
<!-- Notice the absence of attribute -->
<my-element></my-element>
… then AngularJS will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception as soon as you'll try to set a value to $scope.myAttribute
. So, as said in the documentation, add an interrogation point in your scope definition:
scope: {
myAttribute: '=?',
},
Then, you can simply set the default value in your controller:
controller: function ($scope) {
if (angular.isUndefined($scope.myAttribute)) {
$scope.myAttribute = true;
}
},
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments