2
所以我想构建一个AngularJS应用程序,并且在使用异步回调时遇到了控制器和指令之间的双向数据绑定问题。我有一个页面控制器,可以从服务器获取数据,然后使用多个自定义窗体指令编辑数据。这里是我的设置: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与所有的数据(但它仍然没有正确的清洁模型) 。 – topgrunt