简体   繁体   中英

ngModel don't upate deep level

When I have a ngModel with more that one level and I modify the value programmatically in the scope, the value is not updated in the UI. If I put a $watch on the same property, it works. How can I fix ngModel

html:

<form ng-controller="testController">
    <input type="text" ng-model="coco.c.c.c">
    <input type="test" ng-model="super.s.s.s">
    <input type="test" ng-model="super2">
</form>

js:

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

app.controller('testController', function ($scope) {
    $scope.super = {
        s: {
            s: {

            }
        }
    };

    $scope.coco = {
        c: {
            c: {

            }
        }
    };

    $scope.$watch('coco.c.c.c', function (value) {
        $scope.super = +value * 2;
        console.log(value);

    });
    $scope.$watch('super.s.s.s', function (value) {
        $scope.super2 = +value * 2;
    });
});
app.controller('testController2', function ($scope) {
    $scope.$watch('coco', function (value) {
        $scope.super = +value * 2;
        console.log(value);
    });
    $scope.$watch('super', function (value) {
        $scope.super2 = +value * 2;
    });
});

angular.bootstrap(document, [app.name]);

http://jsfiddle.net/M5wzt/2/

I think the problem is this line

  $scope.super = +value * 2;

here you are changing what $scope.super is. So You can no more use $scope.super.sss

I have not understood what is that you want to accomplish, though. Maybe something like this?

<form ng-controller="testController">
   <input type="text" ng-model="coco.c.c.c" />
   <input type="text" ng-model="super.s.s.s" />
   <input type="text" ng-model="super2" />
</form>

app.controller('testController', function ($scope) {
    $scope.super = {s:{ s:{ }}}

    $scope.coco = {
        c: {
            c: {

            }
        }
    };

    $scope.$watch('coco.c.c.c', function (value) {
        $scope.super.s.s.s = +value * 2;
        console.log("coco", value);

    });
    $scope.$watch('super.s.s.s', function (value) {
       $scope.super2 = +value * 2;
        console.log("super", value);
    });
});

continuing the previous answer. On line

$scope.super = +value * 2;

you are adding an object to a number creating a nan value, destroying your model reference hence no model since objects are attache and watched by reference this means your input has no model to watch to hence you are braking your chain

http://jsfiddle.net/d65yan/M5wzt/4/

and then you are trying to listen in a controller for changes in the other controllers scope?? thats not going to work sorry you can only watch for thing happening in your scope

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM