简体   繁体   中英

How to set the default value of directive attribute?

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!

Make the attribute optional

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: '=?',
},

Define the default value

Then, you can simply set the default value in your controller:

controller: function ($scope) {
    if (angular.isUndefined($scope.myAttribute)) {
        $scope.myAttribute = true;
    }
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM