如何设置directive属性的默认值?

时间:2014-09-21 12:02:15

标签: javascript angularjs

我正在构建一个指向AngularJS的自定义元素。我的元素将像这样使用:

<my-element my-attribute="false"></my-element>

如果用户未设置my-attribute,我希望默认为true。如何为指令属性指定默认值?目前,我有以下内容:

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>'
  };
});

谢谢!

1 个答案:

答案 0 :(得分:3)

使属性可选

首先,请务必将该属性设为可选。使用您当前的代码,如果您的指令使用...

<!-- Notice the absence of attribute -->
<my-element></my-element> 

...然后,当您尝试将值设置为$scope.myAttribute时,AngularJS将抛出NON_ASSIGNABLE_MODEL_EXPRESSION异常。因此,如上所述in the documentation,在范围定义中添加一个询问点:

scope: {
    myAttribute: '=?',
},

定义默认值

然后,您只需在控制器中设置默认值:

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