我創建了一個包含按鈕的自定義指令。這個按鈕從'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數組 –