angularjs: $scope update when I change a select wi

2019-01-17 17:58发布

问题:

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 is that my scope doesn't change.

Here you can see a quick example... changing the select the scope changes. clicking the buttons the select changes but not the scope.

http://plnkr.co/edit/pYzqeL6jrQdTNkqwF1HG?p=preview

What am I missing?

回答1:

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;
    });
});


回答2:

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..



回答3:

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.



回答4:

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.



回答5:

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
    });