如何检查AngularJS中是否指定了伪指令的方法参数?
发布时间:2020-12-17 08:37:32 所属栏目:安全 来源:网络整理
导读:我创建了一个自定义指令,其中包含一个按钮。此按钮从“callback”属性指定的父作用域调用方法。 !DOCTYPE htmlhtml ng-app="app"head titleSimple directive/title script src="js/lib/angular/angular.js"/script script type="text/javascript" var app =
|
我创建了一个自定义指令,其中包含一个按钮。此按钮从“callback”属性指定的父作用域调用方法。
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>Simple directive</title>
<script src="js/lib/angular/angular.js"></script>
<script type="text/javascript">
var app = angular.module('app',[]);
app.controller('TestController',function($scope) {
$scope.doSomething = function(param) {
alert('Something called with: ' + param);
}
})
app.directive('myDirective',function() {
var ret = {
restrict: 'E',scope: {
user: '@',callback: '&' // bound a function from the scope
},template: '<div>Hello {{user}}<button ng-show="hasCallback()" ng-click="callback({userData: user})">Callback</button>',controller: function($scope) {
$scope.hasCallback2 = function() {
var t = typeof $scope.callback;
return t == 'function';
}
$scope.hasCallback = function() {
return angular.isDefined($scope.callback);
}
}
};
return ret;
});
</script>
</head>
<body ng-controller="TestController">
<my-directive user="cat" callback="doSomething(userData)"></my-directive>
<my-directive user="dog" callback="doSomething(userData)"></my-directive>
<my-directive user="pig"></my-directive>
</body>
</html>
我的问题是: 如何控制模板内按钮的可见性?如果回调属性没有在自定义标签中指定,我想隐藏它(见第3个my-directive标签)。
使用’& ;?’如果未设置属性,则返回undefined。
‘&’ =总是定义回调函数。 ‘& ;?’ =回调函数仅在html模板中定义属性时定义。 bindToController: {
callback: '&?'
},controller: function() {
if (this.callback === undefined) {
// attribute "callback" was not defined
}
}
注意:在Angular 1.4.8中工作。我不知道如果它在旧版本中工作。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
