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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With