0 ajax jquery controller angularjs
我已经试图搜索anwser ...我被卡住了.
我尝试在控制器之间进行通信(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);
});
};
Run Code Online (Sandbox Code Playgroud)
这有什么问题?
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'];
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
谢谢.
问题是您的代码是在"AngularJS world"之外执行的.确切地说,任何应该触发双向数据绑定的外部事件都应该触发AngularJS $ digest循环.有关详细信息,请参见http://docs.angularjs.org/guide/concepts.
现在,回到你的特定问题,你有两个解决方案:
删除jQuery ajax以支持AngularJS $http
服务.这是一个首选的解决方案,它更容易和更好:从jquery $ .ajax到angular $ http
$scope.$apply
在jQuery调用完成时,在方法中包含您的调用以触发$ digest循环
但实际上,放开jQuery ......
归档时间: |
|
查看次数: |
4165 次 |
最近记录: |