그래서 AngularJS 응용 프로그램을 빌드하고 비동기 콜백 함께 사용할 때 컨트롤러 및 지시문 사이의 양방향 데이터 바인딩을 사용하여 몇 가지 문제가 있습니다. 내가 서버에서 데이터를 가져온 다음 여러 가지 사용자 지정 양식 지시문을 사용하여 데이터를 편집하는 페이지 컨트롤러가 있습니다. 여기 내 설정이다 :AngularJs 양방향 databinding 비동기 콜백 함께 작동하지 않는
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($scope):
...
model: { object with data inside it as expected }
...
console.log($scope.model):
Object {} // empty
따라서이 범위 모델을 가지고 로그 만 $ 범위 : 진짜로 이상한 것은이 지침에 이벤트 리스너에서, 두 CONSOLE.LOG 호출이 모순 된 정보를 제공하는 것처럼 보인다입니다 .model은 어떻게 든 비어 있습니다.
감사합니다. 어떤 도움을 주셔서 감사합니다. 정말 감사합니다. 당신이 resolve
에서 데이터를 받으면 컨트롤러가 인스턴스화되기 전에
한 가지주의해야 할 점은 입력 필드 중 하나를 변경하여 양식이 유효하지 않게 된 다음 유효한 것으로 지정하면 지시문의 $ scope.model이 모든 데이터로 업데이트된다는 것입니다 (그러나 올바른 깨끗한 모델은 아직 없습니다) . – topgrunt