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