如何从指令链接内部为选择框设置选定值

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

本文关键字:设置 选择 指令 链接 内部      更新时间:2023-09-26

我有非常基本的指令,其中包含选择下拉列表。现在我正在尝试从内部指令link函数中设置选定的选项。我目前的做法涉及 setTimeout,它看起来过于复杂,似乎不对。正确的"角度"方法是什么?我知道ng-init可能会这样做,但是如何从指令代码中做到这一点?这是我的代码,plunker 在这里 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);
    }
  }
}])

和 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="angular.js@1.3.x" 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>

更改模板以使用 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>

然后简单地在您的链接函数中

     scope.grade=grades[2].id;

无需设置超时等

普朗克链接