JensOlsen112
JensOlsen112

Reputation: 1299

Two-way bind an object of the scope of the directive

I'm trying to create a directive that has a two-way binding to the passed object:

angular.module('app').directive('lmDataBox', function () {
    return {
        restrict: 'A',
        scope: {
            lmdata: '=',
        },
        template: '<input type="text" ng-model="lmdata.displayValue">',
        link: function link(scope, element, attrs) {

            scope.lmdata.displayValue = 'testvalue';
    }
};

However, even though I set "displayValue" to a string the input box is empty.

What am I doing wrong?

Upvotes: 0

Views: 130

Answers (1)

Bricktop
Bricktop

Reputation: 1549

I might have found your problem:

lmdata is probably not set in your parent scope. This means that when you try to set scope.lmdata.displayValue you try to set an undefined scope variable.

To solve this you have to set lmdata in your parent scope like so:

$scope.lmdata = {'displayValue':''};

I have created a working example in plnkr (I only changed the restriction to 'E' for convenience) here

Upvotes: 2

Related Questions