<div ng-controller="MyCtrl">
<button ng-click=addItem()>add Item</button>
<div ng-repeat="item in content">
<my-directive category-options="categoryOptions" item-options="itemOptions" category-option-change="categoryOptionChange(selectedOption)" delete-item="deleteItem(index)" index={{index}}></my-directive>
</div>
</div>
myApp.directive('myDirective', function() {
return {
scope: {
categoryOptions: "=",
deleteItem: "&",
index: '@',
itemOptions: "=",
categoryOptionChange: "&"
},
restrict: 'AE',
template: "<p>\r" +
"\n" +
" <select ng-model=\"categoryOptions.selectedOption\" ng-options=\"option as option.name for option in categoryOptions\" ng-change=\"categoryOptionChange({selectedOption:categoryOptions.selectedOption})\">\r" +
"\n" +
" <option value=\"\">choose</option>\r" +
"\n" +
" </select> \r" +
"\n" +
" <select ng-model=\"itemOptions.selectedOption\" ng-options=\"option as option.name for option in itemOptions\">\r" +
"\n" +
" <option value=\"\">choose</option>\r" +
"\n" +
" </select>\r" +
"\n" +
" [<a href ng-click=\"deleteItem({index:index})\">X</a>]\r" +
"\n" +
"</p>\r" +
"\n"
}
});
每次单击时,都会添加一个带有两个选择控件的新项目。基于第一选择控制选择选项,第二选择控制选项改变。 用户可以添加任意数量的项目。 到这里它工作正常。我面临的问题是,如果我添加一个项目并更改选择控件中的选项然后添加一个新项目,那么新添加的项目也会显示先前选择的相同数据。 我知道这是数据绑定问题,但我不知道如何有效地解决这个问题
我添加了JSFiddle
答案 0 :(得分:0)
将控制器附加到指令,并在指令控制器中基于每个指令处理itemOptions。您需要单独存储每个指令的状态,但是您不是 - 您在父作用域上存储所有指令的状态。
答案 1 :(得分:0)
我建议遵循解决方案。可以在 - @sumit Plunker找到一个工作示例 这是代码示例:
var app = angular.module('app', []);
app.controller("mainController", function($scope) {
$scope.content = [];
$scope.addSentence = function() {
$scope.content.push({});
};
$scope.deleteItem = function(index) {
$scope.content.splice(index, 1);
};
$scope.categoryOptions = [{
name: "Books"
}, {
name: "Electronics"
}];
$scope.itemOptions = {
books: [{
name: "Harry Potter1"
}, {
name: "Harry Potter2"
}, {
name: "Harry Potter3"
}],
electronics: [{
name: "Computer"
}, {
name: "Phone"
}, {
name: "Television"
}]
};
});
app.directive('myDirective', function() {
return {
scope: {
categoryData: "=categoryOptions",
deleteItem: "&",
index: '@',
itemData: "=itemOptions",
categoryOptionChange: "&"
},
restrict: 'AE',
templateUrl: "itemSelectTemplate.html",
controller: function($scope) {
$scope.itemOptions = [];
$scope.categorySelectedOption = {};
$scope.itemSelectedOption = {};
$scope.categoryOptionChange = function(selectedOption) {
if (selectedOption !== null) {
switch (selectedOption.name) {
case "Books":
$scope.itemOptions = $scope.itemData.books;
break;
case "Electronics":
$scope.itemOptions = $scope.itemData.electronics;
break;
}
}
}
}
}
});
希望这会对你有所帮助! :)