1

I'm trying to create a custom directive for a drop down control in AngularJS 1.4.4. I can handle the selected event, but i can not get the binding for what is selected in the drop down list.

I want to call this from Html markup the following way.

<my-dropdown-list source="myList" destination="mySelection"  />

The angular js custom directive is here.

(function() {

var directive = function($compile) {
    return {
        restrict: 'E',
        scope: {
            model: '=source',
            selectedValues: '=destination'
        },
        controller: function($scope) {

            $scope.onSelChange = function() {
                alert('called');
                console.log($scope.selectedItem.Code, $scope.selectedItem.Name);
            };
           // $scope.selectedItem is always undefined here.


        },
        link: function ($scope, $elem) {

            var rowHtml =
            '<select ng-options="item as item.Name for item in model" ng-model="selectedItem" ng-change="onSelChange()"></select>';

            $elem.html(rowHtml);
            $compile($elem.contents())($scope.$new());
        }
    };
};
my.directive('myDropdownList', directive);
})();

I'm new to Angular, so this may be something small that i missed here, but i can't seem to get a value for 'selectedItem'

mflair2000
  • 315
  • 3
  • 13
  • It's the classic "dot notation" problem. You need to have your binding properties on an object - `myModel.mySelection` to have it bind with a directive. – codemonkey Sep 08 '15 at 15:29
  • The problem is that you created a new scope for the html you've added to your directive template. But in controller you have access to its parent scope and the parent scope can not see its child. – alisabzevari Sep 08 '15 at 15:40

1 Answers1

0

I find out this in AgularJS document

Note that the value of a select directive used without ngOptions is always a string. When the model needs to be bound to a non-string value, you must either explictly convert it using a directive (see example below) or use ngOptions to specify the set of options. This is because an option element can only be bound to string values at present.

Link: https://docs.angularjs.org/api/ng/directive/select

You should use ngRepeat to generate the list like this post: Angularjs: select not updating when ng-model is updated

Community
  • 1
  • 1
  • I tried using ng-repeat first, with the same problem. I think it is the parent scope cannot see the selected binding, as a comment above suggested. – mflair2000 Sep 08 '15 at 15:58