Javascript ng repeat内的ng选项-can';无法访问$scope中的选定项
我想做以下工作: 我有一个包含所有可能项的数组“all”。 我想在“子集”中创建该数组的子集: js.js:Javascript ng repeat内的ng选项-can';无法访问$scope中的选定项,javascript,angularjs,Javascript,Angularjs,我想做以下工作: 我有一个包含所有可能项的数组“all”。 我想在“子集”中创建该数组的子集: 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'
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>
添加项目:
{{c.name}}
但我得到的是“TypeError:无法设置未定义的”属性“inUse”。我在子作用域中看到inUse属性。这种行为是意料之中的吗?如何访问范围中的选定项
我可以做到以下几点,但我认为这是不对的:
var child = $scope.$$childHead;
for (var i = 0; i < index ; i++) {
child = child.$$nextSibling;
}
$scope.all[index] = child.selectedItem;
var child=$scope.$$childHead;
对于(变量i=0;i
做我想做的事情的正确方法是什么?Charlie,你给了我改变向子集添加项目的方法的想法: JS 这和我想做的不一样,但很管用 HTML
添加项目:
{{c.name}}
在嵌套的ng RepeatBw中使用相同的变量名是没有意义的:该示例可以正常工作,但数组“all”和“subset”的名称是混合的..charlietfl,不明白。为什么没有意义?因为当您使用ng options=“c….
启动一个新变量时,c
已经定义。请尝试将其中一个变量更改为不同的名称,问题可能会自行解决。您需要了解,这些变量名称将用作子作用域属性
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);
}
};
});
<!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>