加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 06:47:54 所属栏目:安全 来源:网络整理
导读:我有一个指令,它应该更新另一个输入. 但是,我找不到从指令中访问其他输入的ng-model的方法 accessOther指令 angular.module('test',[]).directive('accessOther',function() { return { require: '?ngModel',link: function(scope,elem,attr,ngModel) { // n
我有一个指令,它应该更新另一个输入.

但是,我找不到从指令中访问其他输入的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属性访问父范围.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读