나는 이미 anwser를 검색하려고했는데 ... 막혔습니다.AngularJS, jQuery ajax 요청은 항상 두 번 (클릭) 요청해야합니다.
컨트롤러간에 통신을 시도합니다 (http://onehungrymind.com/angularjs-communicating-between-controllers/).
나를 위해 잘 작동합니다.
다음 단계에서 나는 컨트롤러에 보내야하는 ajax 요청을 추가하려고 시도했다.
요청은 업무를 수행하지만 불행히도 항상 두 번째 요청에만 적용됩니다.
AJAX-요청
var request = $.post("http://www.mydomain.com/search.php", { data: "" });
request.done(function(data) {
sharedService.prepForBroadcast(data);
});
};
이 문제점은 무엇을하려고?
JAVASCRIPT
var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
var sharedService = {};
sharedService.message = '';
sharedService.prepForBroadcast = function(msg) {
this.message = msg;
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
function Controller($scope, sharedService) {
$scope.handleClick = function() {
var request = $.post("http://www.mydomain.com/search.php", { data: "" });
request.done(function(data) {
sharedService.prepForBroadcast(data);
});
};
$scope.$on('handleBroadcast', function() {
$scope.message = 'zero: ' + sharedService.message;
});
}
function ControllerOne($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'ONE: ' + sharedService.message;
});
}
function ControllerTwo($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'TWO: ' + sharedService.message;
});
}
Controller.$inject = ['$scope', 'mySharedService'];
ControllerOne.$inject = ['$scope', 'mySharedService'];
ControllerTwo.$inject = ['$scope', 'mySharedService'];
HTML
<script type='text/javascript' src="http://code.angularjs.org/angular-1.0.0rc9.js"></script>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<body ng-app="myModule">
<div ng-controller="Controller">
<button ng-click="handleClick();">read json</button>
</div>
<div ng-controller="ControllerOne">
<input ng-model="message" >
</div>
<div ng-controller="ControllerTwo">
<input ng-model="message" >
</div>
감사합니다.
왜 AJAX 요청에 jQuery를 사용합니까? Angular는 정확하게 동일하고 나머지 각도와 잘 통합되는'$ http' 서비스를 제공합니다. – TheHippo