当我从下拉列表中选择它时,我想在上面的框中添加一个芯片,所以我为此创建了一个过滤器,并且我已经向它传递了一个数组,现在是将芯片添加到上面的框的函数现在不起作用,我不知道为什么。
Controller 代码:
var app = angular.module("myApp", []);
app.controller("appController", function ($scope) {
$scope.selected = [{
'id': 1,
'state': 'UP'
}, {
'id': 2,
'state': 'Delhi'
}];
$scope.options = [{
'id': 1,
'state': 'UP'
}, {
'id': 2,
'state': 'Delhi'
}, {
'id': 3,
'state': 'Haryana'
}, {
'id': 4,
'state': 'WB'
}]
$scope.add = function (item) {
console.log(item);
let insert = true;
item = JSON.parse(item);
for (let i = 0; i < $scope.selected.length; i++) {
if (angular.equals(item, $scope.selected[i])) {
insert = false;
break;
}
}
if (insert == true) {
$scope.selected.push(item);
$scope.selected = angular.copy($scope.selected);
}
};
$scope.remove = function (item) {
let a = item;
let b = $scope.selected.indexOf(a);
$scope.selected.splice(b, 1);
};
});
app.directive("filter", function () {
return {
restrict: 'E',
scope: {
param: '=',
array: '=',
fun: '&'
},
template: "<div ><select ng-change='fun(items)' ng-model='items'><option value='' selected disabled hidden>Choose Here</option> <option ng-repeat='item in array' value={{item}}> {{item.state}}</option> </select>"
};
});
以及 View :
<body ng-app="myApp" ng-controller="appController">
<div>
<div class="chip" ng-repeat="chips in selected">
{{ chips.state }}
<span class="closebtn" ng-click="remove(chips)">×</span>
</div>
</div>
<filter array='options' fun='add(param)'></filter>
</body>
完整代码可以在this fiddle中找到.
最佳答案
我已经看过这段代码了。除了一些错误之外,我看到的唯一问题是将数据从指令范围传递回父级。我的建议是将指令重构为:
app.directive("filter", function() {
return {
restrict: 'E',
scope: {
// selection: '=',
array: '=',
fun: '&'
},
template: `<div>
<select ng-change='fun({ selection: selection })' ng-model='selection'>
<option value='' selected disabled hidden>Choose Here</option>
<option ng-repeat='item in array' value={{item}}> {{item.state}}</option>
</select>
</div>`
};
});
如您所见,您实际上不需要在父级中进行selection
,因为它属于“过滤器”组件。但是,您可以通过将数据传递给 fun
属性(这是您在选择更改时调用的函数)来共享此数据。
Controller 的简化版本将是:
$scope.add = function(selection) {
var item = JSON.parse(selection);
for (let i = 0; i < $scope.selected.length; ++i) {
if ($scope.selected[i].id === item.id) {
return;
}
}
$scope.selected.push(item);
};
$scope.remove = function(item) {
let index = $scope.selected.indexOf(item);
$scope.selected.splice(index, 1);
};
可以找到初始 fiddle 的工作版本 here .
关于javascript - 我正在尝试将函数传递给我创建的指令,但它在 angularjs 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43540615/