Angularjs 动态模型名称
我正在编写一个指令,在获取邮政编码的系统中重复使用Angularjs 动态模型名称,angularjs,angularjs-scope,Angularjs,Angularjs Scope,我正在编写一个指令,在获取邮政编码的系统中重复使用 //postcode grabber app.directive('postcodes', function ($rootScope, $http) { return function (scope, element, attrs) { element.bind('change', function () { var modal_element = angular.
//postcode grabber
app.directive('postcodes',
function ($rootScope, $http) {
return function (scope, element, attrs) {
element.bind('change', function () {
var modal_element = angular.element('#myModal');
var ctrl = modal_element.controller();
var url = '/postage/postcodes/?suburb=' + element.val() + "&target_suburb=" + attrs.targetSuburb + "&target_state=" + attrs.targetState + "&target_postcode=" + attrs.targetPostcode;
ctrl.setModal(url);
modal_element.modal('show');
});
};
});
它会在更改时打开一个引导模式窗口,其中包含一个控制器:
function PostcodesCtrl($scope, $parse) {
$scope.populate = function (suburb, state, postcode, target_suburb, target_state, target_postcode) {
//lets grab the controller of the target postcode
var tpscope = angular.element(target_postcode).scope();
}
}
PostcodesCtrl.$inject = ['$scope', '$rootScope'];
我使用输入元素“ID”(例如#郊区)访问了目标输入字段的范围(tpscope行),但我不确定如何更新ngModel值,因为它们总是不同的名称
这就是为什么我要将target_郊区、target_邮政编码等发送到服务器,然后服务器会有一个ng单击,将它们返回到“populate”函数
是否可以动态访问范围变量?比如$scope[随便什么]。。还是类似的
更新:我发现我可以访问$scope[var]没有问题,但是ng模型名称将有一个小数点。。。例如“模范郊区”——似乎不是这样
如果有人对如何做到这一点有更好的想法,请让我知道 对于带有
的ngModel值,需要进行特殊处理才能在指令中解析并使用它。您需要使用$parse
服务在作用域的上下文中处理模型。差不多
var getter=$parse(attrs.ngModel);
var setter=getter.assign;
setter(scope,!getter(scope));
看到我的答案了吗?你是个传奇!,添加一个答案,以便我可以接受:)