Koustuv Sinha
Koustuv Sinha

Reputation: 1670

Isolate scope fallback in AngularJS

I am trying to build a custom directive for input box, which has input-model as an attribute used as ng-model. This input-model attribute is two way bound with an inner scope variable.

templateUrl:'/components/directives/inputBox.html',
transclude:true,
restrict: 'A',
scope:{
  userInput : '=inputModel'
}

Now the issue is, in the main html when I explicitly provide input-model, then it works fine. But I want a fallback when input-model is not provided, then the two way binding should be removed. The template is like

<input id="searchinput" type="search"
               name="inputBox"
               class="form-control"
               placeholder="{{placeholder}}"
               ng-model="userInput"
               ng-pattern="pattern"> 

So, when I do not provide the input-model attribute in the main html

<div input-box></div>

The binding fails as expected, giving the error :

Error: [$compile:nonassign] Expression 'undefined' used with directive 'inputBox' is non-assignable!

I want to make a fallback to avoid this scenario. How should I proceed?

Upvotes: 0

Views: 351

Answers (2)

Simon Staton
Simon Staton

Reputation: 4505

You can check the defined attributes in the compile method, this will allow you to handle the case before binding takes place.

    return {
    template: '<div>{{userInput}} - test</div>',
    transclude: true,
    restrict: 'A',
    scope: {
        userInput: '=inputModel'
    },
    compile: function(element, attrs, transclude) {
        if (!attrs.inputModel) {
            attrs.inputModel = 'userInput';
        }
        return {
            pre: function(scope, element, attrs) {},
            post: function(scope, element, attrs) {}
        }
    }
};

http://jsfiddle.net/anf4ryzL/

Upvotes: 1

Jeff Ling
Jeff Ling

Reputation: 1032

Will this solution work for you?

Angular directive with default options

Upvotes: 1

Related Questions