Writing a angularjs directive which initializes the model of a select box by finding the selected option

301 Views Asked by At

I have a server side template(ZPT) where in I am populating a select box as:

<select id="state">
  <option value="">----</option>
  <option tal:repeat="state states" tal:attributes="value state/code" tal:content="state/desc"></option>
</select>

I want to add some dynamic stuff to the select box using angularjs and I am writing an angular directive which can initialize the model on the select box. Previously I was setting the initial value of my ng-model using $scope.state = document.getElementById('state').value but I was advised that DOM manipulation should be done in a directive and not in controller.

So now I'm trying to write this directive which will be common for all the HTML tags rendered by the template and adding special case for select tags.

.directive('initModelFromServer', function() {
return {
   restrict: 'A',
   require: 'ngModel',
   link : function(scope, elm, attr, ngModelCtrl) {
       if (attr.type === 'text'){
           ngModelCtrl.$setViewValue(elm.val());
       }
       var tagName = elm[0].nodeName;
       if (tagName === 'SELECT'){
           ngModelCtrl.$setViewValue(elm[0].children(elm[0].selectedIndex));
       }
   }
};

and then applying the directive to my tags as:

<select id="state" ng-model="state" init-model-from-server>
  <option value="">----</option>
  <option tal:repeat="state states" tal:attributes="value state/code" tal:content="state/desc"></option>
</select>

The problem is when I do elm[0].selectedIndex when I find the select tag it's always set as 0. I've tried other approaches by finding the children of select and finding selected attribute on an option but haven't been able to achieve the same functionality.

I don't want to send a json object from my server side template and assign it to angular variables because then it would be more data to be passed to the client. I would rather want a directive which can initialize model directly using DOM manipulation in the link method for all sort of HTML tags rendered by the server.

Thanks in advance!

0

There are 0 best solutions below