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

时间:2016-02-03 23:35:09

标签: javascript angularjs

我想做以下事情:

我有一系列所有可能的项目'全部'。 我想在'subset'中创建该数组的子集:

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>

但我得到'TypeError:无法设置属性'inUse'of undefined'。我在子范围中看到了inUse属性。这种行为有望吗?如何访问我的范围内的所选项目?

我可以做以下事情,但我不相信这是正确的:

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

$scope.all[index] = child.selectedItem;

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

1 个答案:

答案 0 :(得分:1)

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

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>