Michael Natkin
Michael Natkin

Reputation: 524

Angular - two-way binding through an ng-switch

I have a directive with scope and a two-way '=' binding to a parent-scope value (yes, inside an object to avoid inheritance problems.) The directive's template in turn contains an ng-switch, which of course creates another scope. Inside the ng-switch I want to have a textarea bound to the original value. It gets initialized correctly, but when the user edits the value, the parent scope value doesn't change.

var myApp = angular.module('myApp', []);

myApp.directive('csContenteditable', function () {
    return {
        restrict: 'A',
        scope: {
            content: "=",
            editMode: "=csContenteditable",
        },
        template: 
            "<div ng-switch='editMode'>" +
                "<div ng-switch-when='false'>{{content}}</div>" +
                "<div ng-switch-when='true'><textarea ng-model='content'/><div>" +
            "<div>"

    };
});


function MyCtrl($scope) {
    $scope.editMode = false;
    $scope.values = {value: 'foo'}
}

What is the right way to do this? I can use ng-show instead of ng-switch and it works, b/c there is no extra scope but makes my DOM a lot heavier than necessary in my actual real-world case.

Demo: http://jsfiddle.net/LF5UL/

Upvotes: 1

Views: 1650

Answers (2)

Poyraz Yilmaz
Poyraz Yilmaz

Reputation: 5857

it is a scope issue... ng-if directive creates a new scope that why your model is not updated...

if you use primitive object like you used there child scope create new instance instead of inherite from parent scope

bind values instead of values.value which is a primitive variable and your directive scope don't shadow/hide your original object...

here is your html

<div content="values" cs-contenteditable="editMode" />

and here is directive's template

"<div ng-switch='editMode'>" +
   "<div ng-switch-when='false'>{{content.value}}</div>" +
   "<div ng-switch-when='true'><textarea ng-model='content.value'/><div>" +
"<div>"

for more information look understanding $scope...

and here is updated JSFIDDLE...

UPDATE

I recommend using complex object instead of using $parent because if you use some directive in your directive which create new scope like ng-if break your $parent solution, here is example JSFIDDLE...

Upvotes: 2

Michael Natkin
Michael Natkin

Reputation: 524

I'll be darned, I just solved this. The answer is to use $parent.content instead of content in both cases inside the directive.

Upvotes: 0

Related Questions