我在每个ng-repeat中显示两个控件,一个是用于选择地址类型的下拉框,第二个是带有自定义指令的输入。
我想在第二个控件的指令中访问第一个控件中的选定值(在变量aFlag中设置)。我认为aFlag是一个子范围变量,但是我无法在函数toggleAFlag()中检索子范围以设置标志,以及如何在指令中访问该标志。
以下是我的HTML代码
<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
}
}
};
});
答案 0 :(得分:1)
我认为数据模型看起来像这样
$scope.itemList = [{
addressTypes: [{
name: 'add1',
addressType: 'Business'
}, {
name: 'add2',
addressType: 'Non Business'
}]
}];
进行以下更改:
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
}
})
}
的 Demo 强>