Search code examples
angularjsangularjs-directiveangularjs-scope

How to set a default value in an AngularJS Directive Scope?


In AngularJS, I have the following scenario where a directive can accept an optional boolean parameter which should default to true by default, whenever it is not specified.

Example:

<my-directive data-allow-something="false">
    ... this works as expected as no default value should be set in this case ...
</my-directive>

<my-directive>
    ... but in this case i'd like allowSomething to equal true  ...
</my-directive>

I've tried the following approach, but for some reason the true value doesn't stick on allowSomething. making it a '=?' optional two way binding doesn't work neither as my passed value should be a concrete true/false and not a field reference.

angular.module('myApp').directive('myDirective') {
    ...
    controller: function($scope){
        if (!$scope.allowSomething)
            $scope.allowSomething = true;
    },
    ....
    scope: function(){
        allowSomething: '@'
    }
    ...
}

I'm sure there should be a simple way to achieve this, so what am i missing?

The solutions given at the following ticket: AngularJS directive with default options are not sufficient for my needs since the $compile function will prevent the link function from working. plus, the passed-in boolean value is not a reference type and i cannot give it a two-way binding.


Solution

  • I think a better way to check that value is look for an undefined value like this:

    controller: function($scope){
        if (angular.isUndefined($scope.allowSomething))
            $scope.allowSomething = true;
    }
    

    I had the same issue once and this worked for me. I think the best method is to use angular's methods for handling things.