Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access ng-model of other element from within directive

Tags:

angularjs

I have a directive which is supposed to update another input.

However, I cannot find a way to access the ng-model of the other input from within the directive

accessOther directive

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() {
});

In the below code, The accessOther directive is in #current but is trying to change #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

Additionally, is it possible to change #parent from within the directive too?

like image 665
xiankai Avatar asked Sep 26 '22 19:09

xiankai


1 Answers

Please check working demo: Plunker.

Add this to the directive:

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

You can access the parent scope using $parent property on the directive scope object.

like image 96
Joy Avatar answered Sep 30 '22 06:09

Joy