spirytus
spirytus

Reputation: 10946

How to set selected value for select box from inside directives link

I have very basic directive that contains select dropdown. Now I'm trying to set selected option from inside directives link function. The way I currently do it involves setTimeout and it just seem overly complicated and doesn't seem right. What is the proper "angular" way to do this? I know of ng-init would probably do but how to do it from directive code? Thats my code and plunker is here http://plnkr.co/edit/2RFMTXy2iaeiiJxdPCTS?p=preview:

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

app.directive("myDirective",[function() {

  return {
    replace: true,
    scope: {},
    templateUrl: "myDirective.html",
    link: function(scope,elem,attr) {
      var grades=[{
        id: 100, name: "white"},
        {id: 200, name: "blue"},
        {id: 300, name: "purple"}
        ]

      scope.grades=grades; 

      // selct box in DOM is not populated here yet with grade
      // and so setting will not have any effect
      // so I put this in a queue so browser have a chance
      // to update DOM and then I set selcted option

      setTimeout(function() {
        scope.grade=grades[2].id; 
        scope.$apply();
      },0);

    }
  }
}])

And html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js" data-semver="1.3.7"></script>
    <script src="app.js"></script>

  <script type="text/ng-template" id="myDirective.html">
    <select ng-model="grade">
    <option ng-repeat="grade in grades" value="{{grade.id}}">{{grade.id}} {{grade.name}}</option>
    </select>
    </script>

    </head>

  <body>
    <div my-directive></div>
  </body>

</html>

Upvotes: 0

Views: 641

Answers (1)

harishr
harishr

Reputation: 18055

change your template to use ng-options

<script type="text/ng-template" id="myDirective.html">
    <select ng-model="grade" ng-options="grade.id as grade.id + ' ' + grade.name for grade in grades">
    </select>
</script>

and then simply in your link function

     scope.grade=grades[2].id;

no need of setTimeout etc

PLUNKER LINK

Upvotes: 1

Related Questions