How to check if a method argument of a directive is specified in AngularJS?

Ferenc T picture Ferenc T · Feb 21, 2014 · Viewed 13.9k times · Source

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 question is:

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.

Answer

Bulki S Maslom picture Bulki S Maslom · Nov 26, 2015

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

'&' = callback function is defined always.

'&?' = 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
    }
}

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