加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 08:37:32 所属栏目:安全 来源:网络整理
导读:我创建了一个自定义指令,其中包含一个按钮。此按钮从“callback”属性指定的父作用域调用方法。 !DOCTYPE htmlhtml ng-app="app"head titleSimple directive/title script src="js/lib/angular/angular.js"/script script type="text/javascript" var app =
我创建了一个自定义指令,其中包含一个按钮。此按钮从“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。

使用’&amp ;?’如果未设置属性,则返回undefined。

‘&’ =总是定义回调函数。

‘&amp ;?’ =回调函数仅在html模板中定义属性时定义。

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

注意:在Angular 1.4.8中工作。我不知道如果它在旧版本中工作。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读