【发布时间】:2014-04-17 03:01:32
【问题描述】:
所以我正在尝试构建一个 AngularJS 应用程序,但在与异步回调一起使用时,控制器和指令之间的双向数据绑定遇到了一些麻烦。我有一个页面控制器,它从服务器中提取数据,然后使用多个自定义表单指令来编辑数据。这是我的设置:
function pageController($scope, $http) {
// this is what the data will look like
$scope.controllerModel = {
obj1: {},
obj2: {}
}
$http.get('get the data').then(function(data) {
$scope.controllerModel = data; // fill in the data
$scope.$broadcast('formDataReady'); // tell the forms the data is ready
});
}
指令:
module('blah').directive('customForm', function() {
return {
restrict: 'E',
scope: { model: '=' },
transclude: true,
replace: true,
controller: function($scope, $attrs) {
$scope.cleanModel = $scope.model ? _.cloneDeep($scope.model) : {};
$scope.reset = function() {
$scope.model = _.cloneDeep($scope.cleanModel);
};
$scope.isClean = function() {
return _.isEqual($scope.model, $scope.cleanModel);
};
// Let page controllers tell the from when the model has been loaded
$scope.$on('formDataReady', function() {
console.log('custom-form: resetting the clean model');
$scope.reset();
console.log($scope);
console.log($scope.model);
});
$scope.reset();
},
template:
'<div>' +
'<form name="form" novalidate>' +
'<div ng-transclude></div>' +
'<div class="form-actions">' +
'<button class="btn btn-primary" ' +
'ng-click="save()" ' +
'ng-disabled="form.$invalid || isClean()">' +
'Save</button>' +
'<button class="btn" ' +
'ng-click="reset()" ' +
'ng-disabled=isClean()>' +
'Cancel</button>' +
'</div>' +
'</form>' +
'</div>'
};
});
还有一点html:
<div ng-controller="pageController">
<custom-form model="controllerModel.obj1">
<!-- inputs with ng-model to edit the data -->
</custom-form>
<custom-form model="controllerModel.obj2">
<!-- inputs with ng-model to edit the data -->
</custom-form>
</div>
问题是指令的模型没有因为异步回调而更新。 真正奇怪的是,在指令的事件监听器中,这两个 console.log 调用似乎给出了矛盾的信息:
console.log($scope):
...
model: { object with data inside it as expected }
...
console.log($scope.model):
Object {} // empty
所以在第一个日志中,范围有模型,但 $scope.model 不知何故为空。
非常感谢您对此提供的任何帮助。真的,真的很感激。
【问题讨论】:
-
需要注意的一点是,通过更改其中一个输入字段导致表单变为无效然后有效会使用所有数据更新指令的 $scope.model(但它仍然没有正确的干净模型)。
标签: angularjs data-binding asynchronous