我创建了一个包含按钮的自定义指令。这个按钮从'callback'属性指定的父作用域中调用一个方法。如何检查AngularJS中是否指定了指令的方法参数?
<!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标记),我想隐藏它。 当我检查typeof的回调,我总是得到'功能'和angular.isDefined(...)也返回true。
检查指令的链接函数中的attrs数组 –