所以我有一个回调函数,它从dom返回一个数据对象(有一个项目列表,每次你选择一个项目时它都将它作为一个对象返回)。这是回调函数:
$scope.fClick = function( data ) {
$scope.x = data;
}
当您从下拉列表中选择项目时,从fClick返回的对象如下所示:{ name: "English", ticked: true }
当您从下拉列表中取消选择它时,它将返回如下内容:
{ name: "English", ticked: false }
现在我保留一个像$ scope.output这样的数组来维护返回对象的列表。但是,我想要做的是只有在输出中没有具有相同属性“name”值的对象时才将从scope.fClick返回的对象添加到$ scope.output。所以现在在我的实现中,{ name: "English", ticked: false }
和{ name: "English", ticked: true }
都被添加到数组中。相反,我希望它更新已打勾的属性。因此,例如,如果$scope.output = { name: "English", ticked: false }
然后scope.fClick返回{name:“English”,则勾选:true}。当我将此值推送到$ scope.output时,我希望它更新现有对象的tick属性,以便$scope.output = { name: "English", ticked: false }
成为$scope.output = { name: "English", ticked: true }
这就是我的尝试:
$scope.fClick = function( data ) {
$scope.x = data;
}
$scope.$watch(function () {
return $scope.y = $scope.x;
},function (newValue, oldValue) {
var id = $scope.output.indexOf(newValue);
if(id === -1){
$scope.output.push(newValue);
}
else {
$scope.output[id].tick = newValue.tick;
}
console.log($scope.output);
},true);
我如何使这项工作?
答案 0 :(得分:1)
设置并获取Angularjs的选定值,名称和文本 isteven-multi-select
<div isteven-multi-select
input-model="marks"
output-model="filters.marks"
button-label="name"
item-label="name"
tick-property="ticked"
selection-mode="multiple"
helper-elements="all none filter"
on-item-click="fClick( data )"
default-label="Select marks"
max-labels="1"
max-height="250px">
</div>
添加项目
$scope.marks= [
{ name: 'Mark I', value: 'Mark i', text: 'This is Mark 1', ticked: true },
{ name: 'Mark II', value: 'Mark ii', text: 'This is Mark 2' },
{ name: 'Mark III', value: 'Mark iii', text: 'This is Mark 3' }
];
获取所选项目(更改时)
$scope.fClick = function (data) {
console.log(data.name);
console.log(data.value);
console.log(data.text);
return;
}
(动态选择项目)
$scope.abc = function (data) {
console.log(data.element1, data.element2);
angular.forEach($scope.marks, function (item) {
if (item.value == data.element1) {
item.ticked = true;
}
else {
item.ticked = false;
}
});
}
取消选择项
$scope.marks.map(function (item) {
if (item.value == "")
item.ticked = true;
else
item.ticked = false
});
答案 1 :(得分:0)
你可以通过&#34;模拟&#34; 键/值地图。
<强>控制器强>
(function(){
function Controller($scope) {
$scope.data = [
{name: 'English', ticked: true},
{name: 'French', ticked: false}
];
//Represent a map key - value
$scope.output = {};
$scope.update = function(index){
//Change the ticked value by opposite
$scope.data[index].ticked = !$scope.data[index].ticked;
//Set the value to our map
$scope.output[index] = $scope.data[index].ticked;
}
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
此处,当您更新$scope.output
时,如果密钥存在,它将按新值清除它,而不会创建新的键/值对。
<强> HTML 强>
<body ng-app="app" ng-controller="ctrl">
<ul>
<li ng-repeat="item in data">{{item.name}} {{item.ticked}} <button type="button" ng-click="update($index)">update</button></li>
</ul>
</body>