2013-05-03 36 views
0

我已經嘗試搜索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> 

謝謝。

+0

爲什麼你使用jQuery的AJAX請求。 Angular具有'$ http'服務,它完全相同,並且與角度的其餘部分很好地集成。 – TheHippo 2013-05-03 18:23:36

回答

8

問題是你的代碼是在「AngularJS世界」之外執行的。準確地說,任何應該觸發雙向數據綁定的外部事件都應該觸發AngularJS $ digest循環。有關詳細信息,請參閱http://docs.angularjs.org/guide/concepts

現在,回到你的具體問題,你有2個解決方案:

  1. 下降jQuery的AJAX支持AngularJS $http服務。這是一個首選的解決方案,它更容易和更好:from jquery $.ajax to angular $http

  2. 環繞你的$scope.$apply方法調用觸發$消化循環時,jQuery的通話結束

不過說真的,只是放手jQuery的...

+5

+1「但是真的,只是放開jQuery ...」 – TheHippo 2013-05-03 18:24:03

+0

謝謝。我將使用$ http。這對我有用。 – Maik 2013-05-03 20:10:08