如何检查指令的方法参数是否在 AngularJS 中指定? [英] How to check if a method argument of a directive is specified in AngularJS?

查看:17
本文介绍了如何检查指令的方法参数是否在 AngularJS 中指定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个包含按钮的自定义指令.此按钮从回调"属性指定的父范围调用方法.

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>

我的问题是:

如何控制模板内按钮的可见性?如果自定义标记中未指定回调属性,我想隐藏它(请参阅第三个 my-directive 标记).当我检查回调的 typeof 时,我总是得到 'function' 并且 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.

推荐答案

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

Using '&?' returns undefined if the attribute has not been set.

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

'&' = callback function is defined always.

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

'&?' = callback function is defined only when attribute is defined in html template.

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

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

Note: Works in Angular 1.4.8. I'm not sure if it works in older versions.

这篇关于如何检查指令的方法参数是否在 AngularJS 中指定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆