Search code examples
angularjsdrop-down-menuangularjs-directiveangular-ngmodel

Selected item in directive not working


I created a select directive and am using this directive twice. I need to see the selected items of both. What should I do?

HTML

<div select-list="items"></div>
<div select-list="items2"></div>

Controller

var myApp = angular.module('myApp',[]);

myApp.controller('mainController', function($scope) {
    $scope.items = [
        {
            name: "1"
        },
        {
            name: "2"
        }
    ];

    $scope.items2 = [
        {
            name: "3"
        },
        {
            name:"4"
        }
    ];

    $scope.selectedValues = [];
});

Select directive

myApp.directive("selectList", function() {
    return {
        restrict: "EACM",
        template: '<select ng-model="selectedValues" ng-options="item.name for item in data"></select>',
        scope: {
            data: '=selectList'
        }
    }
});

I need to add selected items of both "selects" into $scope.selectedValues. I tried through ng-change, but it didn't work.


Solution

  • Your directive use isolated scope, so you can't access from the controller to the directive or from the directive to the controller.

    You have to create a new entry.

    I let you a fiddle that is working :

    https://jsfiddle.net/Lv1q2sh2/1/

    // Code goes here
    var myApp = angular.module('app', []);
    angular.module('app')
    .directive("selectList", function(){
      return {
          restrict: "EACM",
          require: 'ngModel',
          template: '<select ng-model="selected" ng-change="onSelectedValue()" ng-options="item.name for item in data"></select>',
          scope: {
              data: '=selectList'
          },
          link: function (scope, element, attr, ngModel) {
            scope.onSelectedValue = function () {
                ngModel.$setViewValue(scope.selected);
            }
          }
      }
    })
    .controller('mainController', function($scope) {
      $scope.items = [
          {name: "1"},
          {name: "2"}
      ];
      $scope.items2 = [
          {name:"3"},
          {name:"4"}
      ];
      $scope.selectedValues = [];
    });