В моем приложении AngularJS есть флажок. Этот список представляет некоторые интересы пользователя. Пользователь может выбрать один или несколько элементов из списка. HTMLAngularJS: Заполнение списка флажков с двумя массивами JSON и изначально проверено некоторые элементы из одного массива
<html>
<head>
<title>User Interests</title>
<script src="../scripts/angular.min.js"></script>
<script src="../scripts/userinterests.js"></script>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<div ng-app="userinterests">
<form ng-submit="submit()" ng-controller="userinterestsCtrl">
<div ng-repeat="userinterest in userinterests">
<input type="checkbox" checkbox-group /> <label>{{userinterest.interestKey}}</label>
</div>
<input type="submit" id="submit" value="Submit" />
</form>
</div>
</body>
</html>
В моем файле JavaScript первый я получаю список из функции серверной, этот список содержит все интересы. Если этот успех для бэкэнд-звонка, то я вызываю другую функцию, чтобы получить уже выбранные элементы от этого пользователя, это возвращает другой список, который содержит интересы, которые уже выбраны пользователем. Теперь у меня есть два списка (список интересов & список уже выбранных интересов пользователя). Теперь я хочу отобразить список флажков со всеми интересами, но я хочу проверить элементы, которые уже выбраны клиентом.
Это мой Javascript выглядит
var app = angular.module('userinterests', []);
app.controller('userinterestsCtrl', function($scope, $http) {
// Get full interests list
$http({
method : 'POST',
url : './test/userInterests',
headers : {
'Content-Type' : 'application/json'
}
}).success(function(response) {
console.log('response=>' + response);
$scope.interests_array = [];
$scope.userinterests = response;
console.log($scope.userinterests);
// Get already selected interests
$http({
method : 'POST',
url : './test/savedInterests',
headers : {
'Content-Type' : 'application/json'
},
params : {
user_email : localStorage.getItem("user_email")
}
}).success(function(response) {
console.log('response=>' + response);
$scope.savedinterests = response;
console.log(response);
}).error(function(response, status, headers, config) {
console.log('failure');
});
}).error(function(response, status, headers, config) {
console.log("failure");
});
$scope.submit = function() {
console.log('Submiting...');
console.log($scope.interests_array.join(", "));
var user_email = localStorage.getItem("user_email");
var preferences = "[" + $scope.interests_array.join(", ") + "]";
console.log('preferences=>' + preferences);
$http({
method : 'POST',
url : './test/setUserInterests',
headers : {
'Content-Type' : 'application/json'
},
params : {
user_email : user_email,
preferences : preferences
}
}).success(function(response) {
console.log('response=>' + response);
}).error(function(response, status, headers, config) {
console.log('failure');
});
};
}).directive(
"checkboxGroup",
function() {
return {
restrict : "A",
link : function(scope, elem, attrs) {
// Determine initial checked boxes
if (scope.interests_array.indexOf(scope.userinterest.interestKey) !== -1) {
elem[0].checked = true;
}
// Update array on click
elem.bind('click', function() {
var index = scope.interests_array.indexOf(scope.userinterest.interestKey);
// Add if checked
if (elem[0].checked) {
if (index === -1)
scope.interests_array.push(scope.userinterest.interestKey);
}
// Remove if unchecked
else {
if (index !== -1)
scope.interests_array.splice(index, 1);
}
// Sort and update DOM display
// scope.$apply(scope.array.sort(function(a, b) {
// return a - b
// }));
});
}
}
});
выборочные данные
$scope.userinterests = [{
"key": "test1",
"score": 1.0
}, {
"key": "test2",
"score": 1.0
}, {
"key": "test3",
"score": 1.0
}, {
"key": "test4",
"score": 1.0
}, {
"key": "test5",
"score": 1.0
}, {
"key": "test6",
"score": 1.0
}, {
"key": "test7",
"score": 1.0
}, {
"key": "test8",
"score": 1.0
}, {
"key": "test9",
"score": 1.0
}, {
"key": "test10",
"score": 1.0
}, {
"key": "test11",
"score": 1.0
}];
var selectedInterests = [{
"key": "test1",
"score": 1.0
}, {
"key": "test2",
"score": 1.0
}, {
"key": "test3",
"score": 1.0
}];
Я был бы очень ценит, если кто-то может быть настолько любезны, чтобы помочь мне достичь этого.
Спасибо
просто проверить при подготовке UserInterest.interestKey, если savedInterests содержит значение, которое доступно в userInterests, затем отметьте это как отмечено –
loop через userInterests и проверьте каждый элемент, используя метод .contains. если это правда, что в этом элементе нажмите некоторый флаг. –
создать фрагмент скрипки. я буду работать над этим –