Lt.
Lt.

Reputation: 1268

How to pass ng-model by reference?

I'm trying to get an custom input text. This is my view

<div>
    <span>{{label}}</span>
    <input type="text" class="{{class}}" placeholder="{{placeholder}}" ng-style="width?{width: width + 'px'}:{}" ng-model="model"/>
</div>

and this is my controller

    angular.module('inputText', [])
        .directive('inputText', function() {
            return {
                restrict: 'E',
                replace: true,
                scope: {
                    width: '@',
                    label: '@',
                    class: '@',
                    placeholder: '@',
                    model: '@'
                },
                controller: 'InputCtrl',
                templateUrl: 'inputText.html'
            };
        })
        .controller('InputCtrl', ['$scope', function($scope) {

        }]);

The problem is that I'm always getting somothing like the following error message:

Error: [$parse:syntax] Syntax Error: Token 'model' is unexpected, expecting [:] at column 3 of the expression [{{model}}] starting at [model}}].

My question is: How do I should pass the model by reference, in order to get something like:

<input-text label="When?" class="" placeholder="" icon="awesome-icon" width="150" model="{{when}}"></input-text>

Upvotes: 2

Views: 4356

Answers (1)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40296

Define the model as scope: { model: "=" } (= means 2-way binding) and use:

<input ... ng-model="model" />

in the template.

Remember not to use first level properties: I.e. do something like this:

<input-text ... model="form.when"></input-text>

And NOT this:

<input-text ... model="when"></input-text>

In all cases the {{when}} is wrong, it will not be 2-way bound.

Upvotes: 2

Related Questions