ng-repeat中的ng-options - 无法访问$scope中的选定项目

ng-options inside ng-repeat - can't access selected item in $scope

本文关键字:scope 项目 访问 ng-options 中的 ng-repeat      更新时间:2023-09-26

我想执行以下操作:

我有一个所有可能的"全部"项目的数组。我想在"子集"中创建该数组的子集:

JS.js:

var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
  $scope.all = [];
  $scope.subset = [{name: 'n1', inUse: false}, {name: 'n2', inUse: false}, {name: 'n3', inUse: false} ];
  // adding new item in all
  $scope.addItem = function() {
    var newc = {name: '?', inUse: false};
    $scope.all.push(newc);
  };
  $scope.updateC = function(index) {
    // index refers to all array
    $scope.all[index].inUse = false;
    $scope.all[index] = $scope.selectedItem;
    $scope.all[index].inUse = true;
  };
});

HTML.html:

<!doctype html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="utf-8">
    <script type="text/javascript" src="angular-1.4.8.js"></script>
    <script type="text/javascript" src="js.js"></script>
</head>
    <body ng-controller="myController">
        <button ng-click="addItem()">Add Item: </button>
        <div ng-repeat="c in all">
            {{c.name}}
           <select ng-options="c as c.name for c in subset | filter: {inUse: false}" 
                ng-change="updateC($index)"
                ng-model="selectedItem"></select>
        </div>
    </body>
</html>

但是我收到"类型错误:无法设置未定义的属性'inUse'。我在子作用域中看到 inUse 属性。这种行为是意料之中的吗?如何访问我的范围内的选定项?

我可以执行以下操作,但我认为这是不正确的:

var child = $scope.$$childHead;
for (var i = 0; i < index ; i++) {
    child = child.$$nextSibling;
}
$scope.all[index] = child.selectedItem;

我想做的事的正确方法是什么?

查理,你给了我改变向子集添加项目的方式的想法:

.JS

var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
  $scope.subset = [];
  $scope.all = [{name: 'n1', inUse: false}, {name: 'n2', inUse: false}, {name: 'n3', inUse: false} ];
  // adding new item in all
  $scope.addItem = function() {
    if ($scope.selectedItem != null) {
        $scope.selectedItem.inUse = true;
        $scope.subset.push($scope.selectedItem);
    }
  };
});

这与我想做的不一样,但它有效。

.HTML

<!doctype html>
<html lang="en" ng-app="myApp">
    <head>
        <meta charset="utf-8">
        <script type="text/javascript" src="angular-1.4.8.js"></script>
        <script type="text/javascript" src="js.js"></script>
    </head>
    <body ng-controller="myController">
        <select ng-options="c2 as c2.name for c2 in all | filter: {inUse: false}" 
                ng-model="selectedItem"></select>
        <button ng-click="addItem()">Add Item: </button>
        <div ng-repeat="c in subset">
            {{c.name}}
        </div>
    </body>
</html>