我已經嘗試搜索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>
謝謝。
爲什麼你使用jQuery的AJAX請求。 Angular具有'$ http'服務,它完全相同,並且與角度的其餘部分很好地集成。 – TheHippo 2013-05-03 18:23:36