Question

So I can't seem to quite figure this out. Basically, I am building a directive which consists of options, and I want to define those options in the directive, but define the default option in my controller. It seems to render fine, but the default option is not being selected. any hints? here is the Plunkr

    angular.module('app', [])
  .controller('Ctrl', function ($scope) {
    $scope.defaultSearchRange = 3;  
  })
  .directive('dateRange', function () {
    return {
      restrict: 'A',
      scope: {
        searchRange: '='
      },
      replace: true,
      template: '<div><select ng-model="searchRange"><option ng-repeat="option in options" value="{{option.value}}">{{option.name}}</option></select></div>',
      controller: function ($scope) {
        $scope.options = [
            { name: '',             value: 0 },
            { name: 'Today',        value: 1 },
            { name: 'Yesterday',    value: 2 },
            { name: 'Last 7 Days',  value: 3 },
            { name: 'Last 30 Days', value: 4 },
            { name: 'Month to Date',value: 5 },
            { name: 'Year to Date', value: 6 }
        ]
      }
    }
  })
Était-ce utile?

La solution

You are not able to set the default because ng-repeat by default will not take into account ng-model.

Here is a forked plunker that is working.

I would suggest to use ng-options instead of ng-repeat. The track by variation will allow you to set the selected value. It must be in the same "object format" to work though.

Here is the modified code:

angular.module('app', [])
  .controller('Ctrl', function ($scope) {
    $scope.defaultSearchRange = 3;
  })
  .directive('dateRange', function () {
    return {
      restrict: 'A',
      scope: {
        searchRange: '='
      },
      replace: true,
      template: '<div><select ng-model="selected" ng-options="o.name for o in options track by o.value"></select></div>',
      link: function (scope) {

        scope.selected = { value: scope.searchRange };

        scope.$watch('selected', function(selected) {

          scope.searchRange = selected.value;
        });

        scope.options = [
            { name: '',             value: 0 },
            { name: 'Today',        value: 1 },
            { name: 'Yesterday',    value: 2 },
            { name: 'Last 7 Days',  value: 3 },
            { name: 'Last 30 Days', value: 4 },
            { name: 'Month to Date',value: 5 },
            { name: 'Year to Date', value: 6 }
        ];
      }
    }
  })

Note: the above code is mapping into a new directive scope property selected. If the controller wanted to pass an object instead of a just the number value, this would not be necessary. Since the value is mapped in, we must $watch and then map the actual selected value back out.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top