2013-02-26 39 views
0

我想知道jQuery UI「autocompleteselect」事件和一些AngularJS事件之間是否存在已知衝突?jQuery UI「autocompleteselect」事件和AngularJs事件之間是否存在衝突?

這裏是我的情況: 我有一個表,並自動完成輸入

<label for="addFruit">Add a fruit</label> 
<input type="text" fruit-autocomplete ng-model="fruit"/> 

<table> 
    <thead> 
     <tr> 
      <th>Label</th> 
      <th>Delete</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr ng-repeat="fruit in fruits | orderBy:fruitsOrder"> 
      <td> 
       {{fruit.label}} 
      </td> 
      <td> 
       <a title="Remove" href="javascript:void(0)" ng-click="rmFruit(fruit)"> 
        Remove 
       </a> 
      </td> 
     </tr> 
    </tbody> 
</table> 

我已經說過我是自動完成的指令

app.directive('fruitAutocomplete', ['$http', function($http){ 
    return function(scope, element, attrs){ 

     element.autocomplete({ 
      select : function(event, ui){ 
       scope.fruit = ui.item; // Stores the selected fruit 
       scope.addFruit(); // Perform addFruit() 
      }, 
      source: ... //Get my custom Json source 
     }).data('autocomplete') .... // Render in ul 

    }; 
}]); 

,這裏是內容的一部分,我控制器

/* 
* Methods 
*/ 
// Add a fruit method 
$scope.addFruit = function(){ 
    this.fruits.push({'label' : 'test'}); // Add a new fruit to fruits 
}; 

// Remove a fruit method 
$scope.rmFruit = function(fruitToRemove){ 
    var index = this.fruits.indexOf(fruitToRemove); 
    this.fruits.splice(index, 1); 
}; 

$scope.fruit = null; // the selected fruit 
$scope.fruits = fruitsList; // fruitList is the object containing all the fruits 
$scope.fruitsOrder = 'label'; 

一切工作正常!除非我在自動完成列表中選擇了一些內容。 事實上,當我選擇一個項目時,select選項被很好地解僱,並且scope.addFruit()也是(我的$scope.fruits對象也被更新了!)。但我的table沒有立即更新!

所以我試着添加一個按鈕「添加」,這將啓動與我的自動完成相同的方法select。就像這樣:

<button type="submit" ng-click="addFruit()"> 
    Add 
</button> 

當點擊scope.addFruit()被解僱,奇怪的是,我的table立即更新!

我搜索並發現,當我在我的自動完成列表中選擇某些內容,然後在我的自動填充字段中輸入內容時,我的table已更新。所以似乎某處發生了「變更」事件。

也許你們中的一些人遇到過這種情況,或者我只是在我的代碼中某處丟失了一點。也許我應該使用$watch?或另一種方法?

感謝您的幫助:)

回答

2

你應該嘗試用包裝$範圍的「選擇」回調。$應用功能。

... 
    select : function(event, ui){ 
    scope.$apply(function(){ 
     scope.fruit = ui.item; // Stores the selected fruit 
     scope.addFruit(); // Perform addFruit() 
    }); 
    }, 
    ... 

您可以在Scope Docs瞭解更多關於$ apply功能的信息。

+0

哇謝謝你的回覆:)它完美的作品。我錯過了這個方法,謝謝! – 2013-02-26 17:47:46

+0

@JulienRodrigues感謝您抽出寶貴時間撰寫實用和可回答的問題。 – Stewie 2013-02-26 17:57:39