如何在angular指令中设置默认参数?
以下是html中的指示:
<product product="product" isfavorites="true"></product>
我希望isfavorites
拥有默认值false
。因此,如果未设置为true
,请返回false
。
我怎么能这样做?
答案 0 :(得分:1)
在Javascript中,未定义的属性(例如isfavorite
)被视为假布尔值。在你的指令中你应该声明isfavorite
属性,该属性将自动为假。
$scope.isfavorite; //this is undefined, therefore evaluated as false
如MDN文档中所述:
如果省略value或者为0,-0,null,false,NaN,undefined或空字符串(“”),则对象的初始值为false。
答案 1 :(得分:0)
正如@ gaurav5430所说,你可以在链接功能中检查它。所以为此使用attrs
param
并获取该值。如果该值为空,那么false
则为true
。
// Code goes here
var app = angular
.module('MyApp', [
])
.controller('Main', ['$scope', function ($scope) {
var self = this;
self.products = [{"productName":"a","id":12},{"productName":"b","id":"34"}];
self.test = function(name){
alert(name);
}
}])
.directive('product', ['$compile', function($compile) {
return {
restrict: 'E',
transclude: true,
scope: {
products: '=',
ngModel : '=',
isfavorites:'@'
},
controller:"Main as myCtrl",
link: function(scope, element, attrs) {
console.log(attrs.isfavorites);
if(attrs.isfavorites == '')
alert("false")
else
alert("true");
var template =
'<ul>' +
'<li data-ng-repeat="product in products |filter:{id:ngModel}" ng-click="myCtrl.test(product.productName)" >' +
'{{product.productName}}' +
'</li>' +
'</ul>';
// Render the template.
element.html('').append($compile(template)(scope));
}
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="main-content" ng-app="MyApp" ng-controller="Main as myCtrl">
<div>
<input type="text" ng-model="myCtrl.pID" />
<product products="myCtrl.products " ng-model="myCtrl.pID" isfavorites></product>
</div>
</div>
答案 2 :(得分:0)
如果您在指令中定义了isfavorite,就像这样
bindToController: {
isfavorite: '=?'
},
并且没有传递它的值,那么默认情况下它是未定义的,它被视为false,如果你想默认为true,那么你可以做这样的事情
controller: function () {
this.isfavorite = true;
// your code
}
答案 3 :(得分:0)
只需在指令的link方法的开头获取变量,并使用directive('product', product);
product.$inject = ['$scope'];
function product($scope){
return {
restrict: 'E',
link: link
};
function link(scope, elmt, attrs){
var isfavorities = scope.$eval(attrs.isfavorities) || false;
// || false is written only for verbosity and code clearness because undefined variables, if evaluated, are false by nature.
// anyway this method is useful when you need default input values quickly
}
}
模式,如下所示:
/home/alex/mydir1