ng-重复范围问题:两级继承

ng-repeat scope issue: two level inheritance?

本文关键字:两级 继承 范围 问题 ng-      更新时间:2023-09-26

我得到了一个对象数组,这些对象具有属性。

我希望能够通过 ng-repeat -> 修改其中一个对象的属性,并且我所做的更改也在原始数组中完成

我试图正确格式化我的数组,以便继承正常:当我在 ng-repeat 中更改时,它会在$scope中更改。但它不会转到原始数组。

我不知道如何更改我的数据/数组以使其工作。

我该怎么办?如何转换我的数据?

这是一个显示这一切的小提琴

ps:我尝试过使用父范围,但正如您在我的例子中看到的那样,我什至没有成功:(无论如何,如果可能的话,建议避免它

这是JS代码:

var myApp = angular.module('myApp',[]);
myApp.controller('myController', function ($scope) {
    //source array
    var origine = [
        {id:"1",name:"elem1"},
        {id:"2",name:"elem2"},
        {id:"3",name:"elem3"} ];
    //what I am doing now
    $scope.element = origine[1];
    //i'd like to transform the array so that I have inheritance and I can avoid using parent scope
    var reference = [];
    var i =0;
    for (var key in origine[2]) {
      if (origine[1].hasOwnProperty(key)) {
          reference[i] = {prop:origine[2][key]};
          i++;
      }
    }
    $scope.element2 = reference;
    $scope.element3 = origine[0];

    $scope.check = function()
    {    
        //to check if the source array is modified
         console.log(origine);
    }
});

在这里 HTML :

<div ng-app="myApp">
    <div ng-controller="myController">
        --------------- BASIC example -----------------
        <br/> Repeat scope
        <div ng-repeat="property in element">
           <input ng-model="property"/>
        </div>     
       <br/>"Parent"
        <input ng-model="element.name"/>
        <br/><input type="button" ng-click="check()" value="check origine"/>
        <br/><br/>--------------- Trying inheritance  -----------------
        <br/> Repeat scope
        <div ng-repeat="property in element2">
           <input ng-model="property.prop"/>
        </div>     
       <br/> "Parent"
        <input ng-model="element2[1].prop"/>       
        <br/><input type="button" ng-click="check()" value="check origine"/>
        <br/><br/>--------------- Trying parent scope -----------------
        <br/> Repeat scope
        <div ng-repeat="property in element3">
           <input ng-model="$parent.property"/>
        </div>     
       <br/> "Parent"
        <input ng-model="element3.name"/>       
        <br/><input type="button" ng-click="check()" value="check origine"/>
    </div>
</div>

这是因为变量是通过引用分配的。

尝试将数组直接分配给作用域并操作该数组,或创建一个作用域方法来推送、拼接、更新该私有数组

如果我理解您的问题正确,您可以按键引用属性以更新它:

<div ng-repeat="(key, property) in element">
    <input ng-model="element[key]"/>
</div>  

小提琴:http://jsfiddle.net/xezbs8gn/7/