Nikolay Nikolay - 1 year ago 145
AngularJS Question

selectivity applied for angularjs select

I try to use selectivity applied to select element, which renders his options via angularjs controller. The problem is that the selectivity applies before angular passes the options to the template. For the protocol - the selectivity styling works fine with static options, but they are not data-binded and static options are not a solution at all.


<select id="roleIds" name="roleIds[]" ng-options=" for role in roles track by" ng-model="selected_roles" multiple></select>


method: "GET",
url: url,
isArray: true
$ =;
$ =;
$scope.roles =;
$scope.selected_roles =;
$scope.selected_accesses =;
$scope.accesses =;

multiple: true,
tokenSeparators: [' ']

How can i achieve this? Is it possible to have nice multiselect while handle the data with angularjs?

Answer Source

You can create an Angular directive and apply selectivity in the directive's link function. You can then add the directive to the html template on the selected element. Since the roles are can be updated and retrieved at a later time, I added a watch to the roles object.

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) {

<link href="" rel="stylesheet" />
<script src=""></script>
<script src=""></script>
<script src=""></script>

<body ng-app="app">
  <div ng-controller="SelectivityCtrl">
    <select id="roleIds" name="roleIds[]" ng-options=" for role in roles track by" ng-model="selected_roles" multiple j-selectivity="roles"></select>



I added an onChange event handler on the new selectivity div which will allows us to properly update the model data. I would recommend writing a custom Angular directive that wraps around the functionality of selectivity. This will allow for much more user friendly design and code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download