Angular - two-way binding through an ng-switch

≡放荡痞女 提交于 2019-12-11 09:19:57

问题


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/

  • Click the "edit mode" checkbox
  • Note the textarea is initialized with "foo"
  • Now type in the textarea.
  • Note the "Current value" in the outer scope doesn't update.

回答1:


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...




回答2:


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



来源:https://stackoverflow.com/questions/22433788/angular-two-way-binding-through-an-ng-switch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!