我尝试使用选择元素的选择性,它通过angularjs控制器呈现他的选项。问题是,在角度将选项传递给模板之前,选择性是适用的。对于协议来说,选择性样式可以很好地处理静态选项,但它们不是数据绑定的,静态选项根本不是解决方案。
html
<select id="roleIds" name="roleIds[]" ng-options="role.name for role in roles track by role.id" ng-model="selected_roles" multiple></select>安古拉杰
$http
({
method: "GET",
url: url,
isArray: true
}).then
(
function(response)
{
$scope.name = response.data.name;
$scope.email = response.data.email;
$scope.roles = response.data.roles;
$scope.selected_roles = response.data.selected_roles;
$scope.selected_accesses = response.data.selected_accesses;
$scope.accesses = response.data.accesses;
jQuery('#roleIds').selectivity({
multiple: true,
tokenSeparators: [' ']
});
}
);我怎样才能做到这一点?在使用angularjs处理数据时,是否有可能进行良好的多选择?
发布于 2016-08-15 17:46:10
您可以创建一个角指令,并在指令的链接函数中应用选择性。然后,可以将该指令添加到选定元素的html模板中。由于角色可以在以后更新和检索,所以我在roles对象中添加了一个watch。
angular.module("app", []);
angular.module("app").controller("SelectivityCtrl", function($scope, $timeout) {
var roles = [{
id: 1,
name: "test"
}, {
id: 2,
name: "blah"
}, {
id: 3,
name: "third"
}];
$timeout(function() {
$scope.roles = roles;
$scope.selected_roles = [];
}, 1000);
});
angular.module("app").directive("jSelectivity", function() {
return {
restrict: 'A',
require: 'ngModel',
scope: {
jSelectivity: "<"
},
link: function(scope, elem, attr, modelCtrl) {
scope.$watch("jSelectivity", function(newValue, oldValue) {
if (newValue !== oldValue) {
var test = jQuery(elem).selectivity({
multiple: true,
tokenSeparators: [' ']
});
$(test).on('change', function(e) {
modelCtrl.$setViewValue($('#roleIds').selectivity('data'));
modelCtrl.$render();
});
}
});
}
}
});<link href="https://arendjr.github.io/selectivity/stylesheets/selectivity-jquery.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://arendjr.github.io/selectivity/javascripts/selectivity-jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="SelectivityCtrl">
<select id="roleIds" name="roleIds[]" ng-options="role.name for role in roles track by role.id" ng-model="selected_roles" multiple j-selectivity="roles"></select>
<p>{{selected_roles|json}}</p>
</div>
</body>
更新
我在新的选择性div上添加了一个onChange事件处理程序,这将允许我们正确地更新模型数据。我建议编写一个自定义的角指令,它围绕着选择性的功能。这将允许更多用户友好的设计和代码。
https://stackoverflow.com/questions/38959054
复制相似问题