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

xia*_*kai 5 angularjs

我有一个指令,它应该更新另一个输入.

但是,我找不到从指令中访问其他输入的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() {
});
Run Code Online (Sandbox Code Playgroud)

在下面的代码中,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>
Run Code Online (Sandbox Code Playgroud)

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

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

Joy*_*Joy 4

请检查工作演示:Plunker

将其添加到指令中:

scope.$parent.pc.data.outside = 'changed `outside` from directive';
scope.$parent.pc.data.parent = 'changed `parent` from directive';
Run Code Online (Sandbox Code Playgroud)

您可以访问指令范围对象上的parent scopeusing属性。$parent