问题描述
我已经创建了包含一个按钮自定义指令。该按钮调用由'回调'属性指定的父范围的方法。
I've created a custom directive which contains a button. This button calls a method from parent scope specified by 'callback' attribute.
<!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-指示标记)。
当我检查的typeof回调,我总是得到功能和angular.isDefined(...)也返回true。
How can I control visibility of button inside template? I'd like to hide it if callback attribute not specified in custom tag (see 3rd my-directive tag).When I check typeof of callback, I always get 'function' and angular.isDefined(...) also returns true.
推荐答案
看着angularjs源$ C $ C,我看到:
Looking at angularjs source code, I see this:
case '&':
parentGet = $parse(attrs[attrName]);
isolateScope[scopeName] = function(locals) {
return parentGet(scope, locals);
};
break;
的 parentGet
是绑定的功能前pression。不幸的是,这是一个局部变量是只可透过封分配给 isolateScope [scopeName]
的功能。
The parentGet
is the bound function expression. Unfortunately, this is a local variable which is only available to the function assigned to isolateScope[scopeName]
via closure.
而不是试图找到一种方式来获得该变量,一个简单的办法就是检查 ATTRS
。尝试:
Instead of trying to find a way to get that variable, a simple solution is just to check the attrs
. Try:
link: function(scope,elem,attrs) {
scope.hasCallback = function() {
return angular.isDefined(attrs.callback);
}
}
这篇关于如何检查是否在AngularJS指定指令的方法参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!