2

我在每个 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
            }
        }
    };
});
4

1 回答 1

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

于 2013-08-15T16:57:09.477 回答