angularjs: $scope update when I change a select with jQuery

前端 未结 5 1991
感动是毒
感动是毒 2020-12-09 05:30

I\'m using a jQuery plugin to \'customize\' my selects.

This plugin fires the change event of the original select when some option is selected.

The problem i

相关标签:
5条回答
  • 2020-12-09 05:51

    When you click the button, angular goes out of its scope and uses jquery to manipulate the data/to perform some action, so we need to exlicitly call $scope.$apply() to reflect the changes back into the scope of the controller. And change your controller to this:

    app.controller('AppCtrl', function($scope) {
        $('button').on('click', function(){
            $scope.selectValue=$(this).data('val');
            $scope.$apply();
        });
    }
    

    By the way you can use jquery event inside the angular..

    0 讨论(0)
  • 2020-12-09 05:53

    You need to access the scope of the dropdown and then apply it as shown below:

    $('button').on('click', function(){
        var newVal = $(this).data('val');
        $('select').val(newVal).change();
    
        var scope = angular.element($("select")).scope();
        scope.$apply(function(){
            scope.selectValue = newVal;
        });
    });
    
    0 讨论(0)
  • 2020-12-09 05:53

    It's best not to mix DOM manipulation with Angular. Try the following for your button HTML:

    <button class="setVal" ng-click="selectValue=1">Set 1</button>
    <button class="setVal" ng-click="selectValue=2">Set 2</button>
    <button class="setVal" ng-click="selectValue=3">Set 3</button>
    

    I tried the above in your Plunker and it worked.

    0 讨论(0)
  • 2020-12-09 06:04

    In your jQuery put auto trigger e.g

     $('#input').click(function(){
          $('#input').val('1');
          $('#input').trigger('input'); //add this line this will bind $scope Variable
        });
    
    0 讨论(0)
  • 2020-12-09 06:11

    Ideally in angularJS, controller should not update DOM reference directly. If you want to achieve same thing, you should expose one method over $scope and use "ng-click" directive.

    If you want to achieve same using jQuery, it should go into directive as

    $scope.$apply()
    

    to update the scope.

    0 讨论(0)
提交回复
热议问题