angularjs – 从指令中访问其他元素的ng-model

前端之家收集整理的这篇文章主要介绍了angularjs – 从指令中访问其他元素的ng-model前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个指令,它应该更新另一个输入.

但是,我找不到从指令中访问其他输入的ng-model的方法

accessOther指令

angular.module('test',[])
.directive('accessOther',function() {
  return {
    require: '?ngModel',link: function(scope,elem,attr,ngModel) {
      // ngModel here only refers to the current input
      ngModel.$setViewValue('test');

      // how to get access/modify another input? (ie. #outside)
    }
  }
})
.controller('parentController',function() {
  var pc = this;
  pc.data = {};
})
.controller('nestedController',function() {
});

在下面的代码中,accessOther指令位于#current但正在尝试更改#outside

<body ng-app="test" ng-controller="parentController as pc">
    <input type="text" ng-model="pc.data.parent" id="parent" placeholder="parent">

    <div ng-controller="nestedController as nc">
        <input type="text" ng-model="pc.data.outside" id="outside" placeholder="outside">
        <br>
        <input type="text" ng-model="pc.data.current" id="current" access-other placeholder="current">
    </div>
</body>

plnkr:
http://plnkr.co/edit/j34GKypDW4h6sZgsMCaA?p=preview

另外,是否可以在指令中更改#parent?

解决方法

请查看工作演示: Plunker.

将此添加到指令:

scope.$parent.pc.data.outside = 'changed `outside` from directive';
scope.$parent.pc.data.parent = 'changed `parent` from directive';

您可以使用指令范围对象上的$parent属性访问父范围.

猜你在找的Angularjs相关文章