如何检查AngularJS中是否指定了指令的方法参数?

Fer*_*c T 39 parameters scope directive callback angularjs

我创建了一个包含按钮的自定义指令.此按钮从'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>
Run Code Online (Sandbox Code Playgroud)

我的问题是:

如何控制模板内按钮的可见性?如果在自定义标记中未指定回调属性,我想隐藏它(请参阅第3个my-directive标记).当我检查回调类型时,我总是得到'function'而angular.isDefined(...)也返回true.

Bul*_*lom 87

使用'&?' 如果尚未设置属性,则返回undefined.

'&'=始终定义回调函数.

'&?' =只有在html模板中定义属性时才定义回调函数.

bindToController: {
    callback: '&?'
},
controller: function() {
    if (this.callback === undefined) {
        // attribute "callback" was not defined
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:适用于Angular 1.4.8.我不确定它是否适用于旧版本.

  • 这在1.3.18中不起作用,无论是否在DOM中定义,它总是在包装函数中连接. (3认同)
  • 这非常有效,是一种更优雅的解决方案.应该是正确的答案. (2认同)

Kha*_* TO 45

看看angularjs的源代码,我看到了这个:

case '&':
    parentGet = $parse(attrs[attrName]);
    isolateScope[scopeName] = function(locals) {
         return parentGet(scope, locals);
    };
    break;
Run Code Online (Sandbox Code Playgroud)

parentGet是结合的函数表达式.不幸的是,这是一个局部变量,只能用于分配给isolateScope[scopeName]via闭包的函数.

一个简单的解决方案就是检查一下,而不是试图找到获得该变量的方法attrs.尝试:

link: function(scope,elem,attrs) {

      scope.hasCallback = function() {
        return angular.isDefined(attrs.callback);
      }
    }
Run Code Online (Sandbox Code Playgroud)

DEMO

  • @Ferenc T:如果对你有帮助,你可以将答案标记为已被接受.谢谢 (2认同)