Call Angular Function with Jquery

前端 未结 7 1825
遇见更好的自我
遇见更好的自我 2020-12-04 21:59

How to call angular function when data in text box? here is my code

html




        
相关标签:
7条回答
  • 2020-12-04 22:15

    You can access the scope of an angular element if you have an ID tag attached to the same DOM element as the ng-controller:

    the DOM:

    <div id="mycontroller" ng-controller="mycontroller"></div>
    

    your controller:

    function mycontroller($scope) {
       $scope.myfunction = function() {
          //do some stuff here
       }
    }
    

    in jquery you do this and it will access that controller and call that function :

    angular.element('#mycontroller').scope().myfunction();
    

    Do remember to call

    angular.element('#mycontroller').scope().$apply() 
    

    if you update a function variable within scope in myfunction, it will not work otherwise (thanks @andersh)

    0 讨论(0)
  • 2020-12-04 22:22

    if you use in your code something like this

    <div id="mycontroller" ng-controller="mycontroller as child"></div>
    

    instead of

    <div id="mycontroller" ng-controller="mycontroller"></div>
    

    the access will be

    angular.element('#mycontroller').scope().child.myFunction();
    

    instead of

    angular.element('#mycontroller').scope().myFunction();
    

    in every case you also need the call

    angular.element('#mycontroller').scope().$apply();
    
    0 讨论(0)
  • 2020-12-04 22:22

    I use something like this:

    var $scope = angular.element($('[ng-controller]')).scope()

    And manipulate the $scope variable. You can check in the console

    0 讨论(0)
  • 2020-12-04 22:27

    I refer to this post, assign function to global object window.

                // In angularJS script
                $scope.foo = function() {
                    console.log('test');
                };
                $window.angFoo = function() {
                    $scope.foo();
                    $scope.$apply(); 
                };
    
                // In jQuery
                if (window.angFoo) {
                    window.angFoo();
                }
    
    0 讨论(0)
  • 2020-12-04 22:31

    I use this code and work well.

     var $scope = angular.element($('[ng-controller="MapCtrl"]')).scope();
    

    and thanks to @Ivan-San answers.

    0 讨论(0)
  • 2020-12-04 22:36

    You can put Jquery code into AngularJS controller like

        $scope.shipchange = function (SelectedShipId ) {
            alert('ShipId =' + SelectedShipId );
        }
    
        $("#Ships").change(function () {
    
            SelectedShipId = $("#Ships").val();
            $scope.shipchange(SelectedShipId );
        })
    
    0 讨论(0)
提交回复
热议问题