我正在研究一个非常简单的小AngularJS指令。我刚刚开始研究它,所以没有那么多。另外,我对AngularJS很新,所以如果可能的话,请尽量简化你的答案!
基本上,这个指令将是一个简单的组合框。如果您不知道组合框的含义,它是一个下拉框,显示用户在搜索栏中键入的文本过滤的结果。
我目前停留的部分是尝试添加类别功能。我希望下拉框中的元素按类别进行组织。这张照片的左侧是我的意思的一个很好的例子:
在我的下面的代码中,我需要做些什么来允许指令的用户传递他们的元素列表以及这些元素被分配到的类别?
的index.html
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="bossy.combobox.js"></script>
<head>
<title>60minish tutorial</title>
</head>
<body>
<div ng-app="test">
<director
data='{elements: ["Apple","Banana","Celery","Carrots"], multi:true}'
></director>
</div>
</body>
</html>
combobox.js:
function testContoller($scope){
$scope.elements = $scope.data.elements;
$scope.list = $scope.elements.slice();
$scope.selectedElements = [];
$scope.submitElement = function(element)
{
if($scope.selectedElements.indexOf(element) == -1)
{
$scope.selectedElements.push(element);
var index = $scope.list.indexOf(element);
$scope.list.splice(index, 1);
}
}
$scope.removeElement = function(element)
{
$scope.list.push(element);
var index = $scope.selectedElements.indexOf(element);
$scope.selectedElements.splice(index, 1);
}
}
function create(){
var template = '{{elements}}'+
'<br>'+
'<div><input type="text" value="John" data-ng-model="name"/></div>'+
'<select>'+
'<option data-ng-repeat="element in list| filter:name" ng-click="submitElement(element)">{{element}}</option>'+
'</select>'+
'<ul>'+
'<li data-ng-repeat="element in selectedElements">{{element}} <button ng-click="removeElement(element)">x</button> </li>'+
'</ul>'+
'<div data-ng-repeat="x in elements| filter:name">{{x}}</div>';
return {
restrict: 'E',
scope: {
data: '='
},
template: template,
controller: testContoller,
};
}
create.$inject = [];
testContoller.$inject = ['$scope'];
angular.module('test',[])
.controller('init', testContoller)
.directive('director', create);
答案 0 :(得分:1)
此处:http://plnkr.co/edit/GzO6I70y1pWm1RedLLEd?p=preview 数据是硬编码的...但我认为你可以从这里拿出来......
HTML
<select>
<optgroup ng-repeat="category in categories" label="{{category}}">
<option ng-repeat="category in products | filter: category" value="volvo">{{category.name}}</option>
</optgroup>
</select>
JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.categories = [];
$scope.products = [
{
category:'fruits',
name:'Apple'
},
{
category:'fruits',
name:'Pearl'
},
{
category:'meat',
name:'Sirloin'
},
{
category:'meat',
name:'Beef'
},
{
category:'meat',
name:'Chicken'
}
];
for (var i = 0; i < $scope.products.length; i++) {
var element = $scope.categories.indexOf($scope.products[i].category);
if (element == -1) {
$scope.categories.push($scope.products[i].category);
}
}
});