我遇到了AngularJS模型更改后更新视图元素的问题。我有一个有2个字段的表单,我希望用户填写其中的一个,并让另一个自动填充(在ng-blur上)。我发布的示例使用人名和社会安全号码(SSN)。通过填写SSN,应用程序执行HTTP调用来获取该SSN的名称,反之亦然。模型更改后角度视图不更新
这里的角指令:
define([
'angular'
], function (angular) {
angular.module('form.formDirective', [])
.directive('formDirective', formDirective);
formDirective.$inject = ["$rootScope", "$sce", "$document", "$translate", "$filter", "$http"];
function formDirective($rootScope, $sce, $document, $translate, $filter, $http) {
var myLink = function ($scope, $element, attrs) {
$scope.setFieldsForName = function(name) {
var url = 'http://some.rest.api/getSsn/' + name;
$http.get(url)
.success(function(data, status, headers, config) {
$scope.personSsn = data.SSN;
})
.error(function (data, status, headers, config) {
// no-op
});
};
$scope.setFieldsForSsn = function(ssn) {
var url = 'http://some.rest.api/getName/' + ssn;
$http.get(url)
.success(function(data, status, headers, config) {
$scope.personSsn = data.name;
})
.error(function (data, status, headers, config) {
// no-op
});
};
};
return {
templateUrl: 'form.directive.html',
restrict : 'EA',
scope : {
field : '=',
model : '=',
renameChildKey: "=",
preview : "=",
delete : '&',
ngDisabled : "=",
isEditData : "="
},
replace : true,
link : myLink
};
}
});
下面是相关的HTML:
<!-- Name -->
<div class="form-group">
<input type="text"
id="{{getId(0)}}"
class="form-control"
placeholder="Name"
ng-model="personName"
ng-blur="setFieldsForName(personName);"/>
</div>
<!-- SSN -->
<div class="form-group">
<input type="text"
id="{{getId(1)}}"
class="form-control"
placeholder="SSN"
ng-model="personSsn"
ng-blur="setFieldsForSsn(personSsn);"/>
</div>
这完全适用于一种情况,例如,填写姓名和取得SSN,或者反过来。但是第一个尝试之后的任何尝试都会调用函数,它会获取数据,更新合适的范围变量,但输入字段值不会反映变量的更新值。
我环顾四周,发现$ scope。$ apply()是一个流行的解决方案,但是它不适用于我,我得到一个错误提示代码已经处于摘要()阶段,所以它不能运行apply()。
如果你有一个想法是怎么回事,我会很感激任何帮助!
附注:你确定你知道'$ q'的用途吗?在你现在的实现中,延迟调用是完全没有用的。 –
尝试使用此:$ http.get(URL)。然后(功能(响应){$ = scope.personSsn response.name; }) –
@czosel,不久,没有。我从其他地方复制了这个潜在的解决方案。 –