Reputation: 6248
I have two controls displayed in each ng-repeat, one is a dropdown box to select an address type, and second is an input with a custom directive.
I want to access the selected value in the first control (set in variable aFlag) in the directive of second control. I think aFlag is a child scope variable but I can't retrieve a child scope in the function toggleAFlag() to set the flag to it as well as how to access that flag in the directive.
Below is my html code
<div ng-app="myapp">
<div ng-controller="AppCtrl">
<div ng-repeat="item in itemList">
<div>
<select ng-options="addressType.name for addressType in item.addressTypes" ng-model="addressType"
ng-change="toggleAFlag(addressType)" >
</select>
</div>
<div> <input type="text" ng-model="value" my-directive></input></div>
</div>
</div>
</div>
Javascript
function AppCtrl(){
$scope.toggleAFlag = function(addressType) {
if (addressType == 'Business')
$scope.AFlag = true;
else {
$scope.AFlag = false;
}
};
}
var myapp = angular.module('myapp',[]);
myapp.directive('myDirective', function(){
return {
require: '?ngModel',
link: function(scope, element, attrs, model){
if (scope.AFlag == true){
//do something on element variable
}
}
};
});
Upvotes: 2
Views: 3044
Reputation: 54524
I assume the data model looks like this
$scope.itemList = [{
addressTypes: [{
name: 'add1',
addressType: 'Business'
}, {
name: 'add2',
addressType: 'Non Business'
}]
}];
Make following changes:
ng-change="toggleAFlag(addressType.addressType)" //pass in the addressType value of the current obj
<input type="text" ng-model="AFlag" my-directive></input> //use AFLag as ng-model, Angularjs binds it automatically
link: function (scope, element, attrs, model) {
scope.$watch(function () { //use $watch to watch any change, so the logic will be triggered if there is any change relating to the scope.
if (scope.AFlag == true) {
//do something on element variable
}
})
}
Upvotes: 1