【问题标题】:How do I access ng-model values inside my directive template?如何访问指令模板中的 ng-model 值?
【发布时间】:2026-01-08 23:15:01
【问题描述】:

我有一个指令,其模板看起来像

<!-- selectList.tpl.html -->
<div ng-if="selectList">
  <p>Id: {{$id}}</p>
  <p>Current list item {{currentItem}}</p>
  <select ng-model="currentItem"
    name="current-item"
    ng-options="item as item.value group by item.group for item in selectList">
    <option value="">All</option>
  </select>
</div>

我正在尝试从我的指令链接函数中访问currentItem 值以创建一个监视函数,即,

app.directive('selectList', [
  "$rootScope",
  "$timeout",
  function (
    $rootScope,
    $timeout
  ) {
    "use strict";

    var getList = function() {
      // ...
    };

    return {
      restrict: 'E',
      templateUrl: 'selectList.tpl.html',
      link: function(scope, element, attrs) {
        scope.selectList = getList();
        scope.currentItem = "";

        console.log("scope id:", scope.$id);

        scope.$watch('currentItem', function(item) {
          $timeout(function() {
            console.log("currentItem is", item);
            angular.element("#console").append("<p>Updated item: " + item + "</p>");
          });
        });
      }
    };
  }
}

但是,在链接作用域下会创建一个子作用域,用于存储对选择框值的更改。如何访问指令链接代码中的选择框更改?

我正在使用 Angular 1.1.5。

这是问题的一个问题(已更新 q 中的代码以反映问题):http://plnkr.co/edit/5eOaRE?p=preview

【问题讨论】:

  • 如果你有几分钟的时间,你能不能设置一个 plunkr。
  • 在不显示指令代码的情况下很难判断你有什么作用域

标签: javascript angularjs angularjs-directive angularjs-scope


【解决方案1】:

ng-if 正在创建另一个范围。因此,当您更新子范围中的值时,它不会更新父范围。

查看更新的插件:http://plnkr.co/edit/3sXPZmhkOJd5uhMJkICx?p=preview

如果需要保留 ng-if,则需要从子作用域调用父作用域中定义的函数。

【讨论】:

【解决方案2】:

您可以在指令中声明一个作用域,并使用一个属性设置双向绑定。例如:

<my-directive attr="myVal">

myApp.directive('myDirective', function() {
    return {
        restrict: 'E',
        scope: {
            attr: '=',
        },
        template: '<select ng-model="attr"> ... </select>',
        replace: true
    };
});

理论上你应该可以直接使用 ng-model,但我遇到了麻烦。如果作用域中声明的属性名和变量名相同,则可以按照我在示例中写的方式使用作用域。否则,您将不得不更具体。

【讨论】: