João Menighin
João Menighin

Reputation: 3225

Optional parameter on Angular Directive

I created a directive on Angular that receives 5 parameters and one of them is an optional array. The way I'm trying to deal with it is like follows:

app.directive('fooDirective', function() {
    return {
        restrict: 'AE',
        scope: {
            param1: '=',
            param2: '=' // optional array
        },
        template: //...
                "<div ng-class='defineClass()'> Message </div>"
                  //...
        controller: function($scope) {

             if (typeof $scope.param2 === 'undefined')
                  $scope.param2 = [];

             console.log($scope.param2);

             $scope.defineClass = function() {
                  if ($scope.param2.length == 0) return 'gray-text';
                  return 'red-text';
             };

             // ......
         }
    }
});

At some point in my code I check for the .length of param2 and if it is undefined it throws a lot of errors. What is driving me nuts is that the console.log() you can see there outputs a [], indicating that the .length of my param should be 0 and the errors on the console are shown after the output of the console.log().

So I guess I am missing something about either the way Angular binds the scopes or the flow that the directive is constructed. I have tried verifing my param on both link and compile phases and got the same problem.

So, what am I missing here? Thanks in advance.

Upvotes: 22

Views: 35387

Answers (1)

ryanyuyu
ryanyuyu

Reputation: 6486

From the angular documentation (see the section for scope bi-directional binding):

= or =attr - set up bi-directional binding between a local scope property and the parent scope property of name defined via the value of the attr attribute.... If the parent scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You can avoid this behavior using =? or =?attr in order to flag the property as optional.

So the solution to make the parameter optional is to change the binding to be an optional two-way binding with the additional ?.

...
scope: {
    param1: '=',
    param2: '=?' // notice the ? makes this parameter optional.
},
...

Upvotes: 53

Related Questions