如何在指令模板中访问ng-model值?

时间:2013-11-28 17:50:09

标签: javascript angularjs angularjs-directive angularjs-scope

我有一个模板看起来像

的指令
<!-- 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>");
          });
        });
      }
    };
  }
}

但是,会在linkscope下创建子范围,该范围存储对选择框值的更改。如何访问指令链接代码中的选择框更改?

我正在使用Angular 1.1.5。

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

2 个答案:

答案 0 :(得分:1)

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

请参阅更新的plunker:http://plnkr.co/edit/3sXPZmhkOJd5uhMJkICx?p=preview

如果你需要保留ng-if你需要从子范围调用父范围中定义的函数。

答案 1 :(得分:0)

您可以在指令中声明范围并使用属性设置双向绑定。例如:

<my-directive attr="myVal">

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

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

相关问题