[英]How to set the default value of directive attribute?
我正在构建一个指向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>'
};
});
谢谢!
首先,一定要使属性可选。 使用您当前的代码,如果你的指令被这样使用......
<!-- Notice the absence of attribute -->
<my-element></my-element>
...然后,当您尝试将值设置为$scope.myAttribute
AngularJS将抛出NON_ASSIGNABLE_MODEL_EXPRESSION异常。 因此,如文档中所述 ,在范围定义中添加一个询问点:
scope: {
myAttribute: '=?',
},
然后,您只需在控制器中设置默认值:
controller: function ($scope) {
if (angular.isUndefined($scope.myAttribute)) {
$scope.myAttribute = true;
}
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.