0
votes

I am creating a set of select boxes, which are bound to a list of values in my view using a directive with a select tag in it, on a div. They are populated with some values, but after they are rendered I want to set a value depending on a already stored value in it.

I am trying to do this by setting model value in ng-init, using the function I call in the controller which initializes the array with the stored values in it.

However, the array is always undefined when the select boxes are rendered and ng-init is called.

How do I ensure the variable is always set when ng-init is called on the select boxes?

    angular.module('myapp')
    .controller('aclCtrl', function()
    {
       $scope.retrieveSetValues(id)
       {
           //.then promise to GET stored values, defined in a factory, sets variable that is accessed in initializeSelects()
       }
    $scope.retrieveSetValues($scope.myID);
    }

View:

selector directive:

.directive("selector", [
    function() {
      return {
        controller: function() {
          this.myValues= ['a', 'b', 'c'];
        },
        require: 'ngModel',
        controllerAs: 'ctrl',
        scope: {
          'ngModel': '='
        },
        template: '<select ng-model="innerModel" ng-change="updateInnerModel()" ng-options="v for v in ctrl.myValues"> </select>',
        link: function(scope, elem, attrs, ngModelController) {
          scope.innerModel = scope.ngModel;
          scope.updateInnerModel = function() {
            ngModelController.$setViewValue(scope.innerModel);
          };
        }
      };
    }
  ])

The problem is that I don't see the variable I am setting in the scope call to retrieveSetValues() in the access ng-init initializeSelects() call.

I have tried both, calling it in the controller and calling it from ng-init just before I try to access the saved values in initializeSelects().

I am new to angular, my understanding of how the whole digest cycle works is newbie level. :(

Any help is appreciated!!

1

1 Answers

0
votes

You can also try that:

function selector() {
return {
    controller: function() {
      this.myValues= ['a', 'b', 'c'];
    },
    require: 'ngModel',
    controllerAs: 'ctrl',
    scope: {
      'ngModel': '='
    },
    template: '<select ng-model="ngModel" ng-options="v for v in ctrl.myValues"> </select>',
    link: function(scope, elem, attrs, ngModelController) {

    }
  };

}

HTML VIEW:

<div selector ng-model="vm.initialValue"></div>

vm.initialValue it will be in your controller.

I created a fiddle for that, check it here

I hope it helps.