【问题标题】:Is there a conflict between jQuery UI "autocompleteselect" event and AngularJs event?jQuery UI "autocompleteselect" 事件和 AngularJs 事件之间是否存在冲突?
【发布时间】:2013-02-26 17:15:03
【问题描述】:

我想知道 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 会更新。因此,某处的“on change”事件似乎正在发生一些事情。

也许你们中的一些人经历过这种情况,或者也许我只是在我的代码中遗漏了一点。也许我应该使用$watch?还是其他方法?

感谢您的帮助:)

【问题讨论】:

    标签: jquery jquery-ui angularjs angularjs-directive


    【解决方案1】:

    您应该尝试使用 $scope.$apply 函数包装您的“选择”回调。

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

    您可以在Scope Docs 中阅读有关 $apply 函数的更多信息。

    【讨论】:

    • 哇,感谢您的回复 :) 它运行良好。我错过了那个方法谢谢!
    • @JulienRodrigues 感谢您花时间写一个实用且可回答的问题。
    猜你喜欢
    • 1970-01-01
    • 2011-12-10
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    相关资源
    最近更新 更多