我创建了一个自定义指令,其中包含一个按钮。此按钮从“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标签)。
当我检查typeof的回调,我总是得到’函数’和angular.isDefined(…)也返回true。