angular js: accessing $scope from jQuery

前端 未结 4 1474
伪装坚强ぢ
伪装坚强ぢ 2021-01-02 07:16

There are several questions like this in stackoverflow. I know. Tried all the answers, but still no luck. My html :

    
相关标签:
4条回答
  • 2021-01-02 07:28

    Angular adds a global angular variable to your window.

    So you can do something like this:

    angular.element("#headline-game").scope().gameContent.headline;
    
    0 讨论(0)
  • 2021-01-02 07:35

    The issue is caused by the order in which the plugins are initialized.

    1. jQuery
    2. AngularJS

    So accessing scope() in a jQuery script on document load will result in undefined, since jQuery is run before Angular.

    The solution to this is to let AngularJS execute jQuery once it is ready, using directives.

    Example :

    Controller

    app.directive("myDirective", function() {
            return {
                restrict: "A",
                scope: {
                    customheadline: "@"
                },
                link: function(scope, elem, attrs) {
                    var country = scope.customheadline;
                    alert(country);
                }
            }
        });
    

    HTML

    <div class="headline" id="headline-game" my-directive customheadline="{{ gameContent.headline }}">
        {{gameContent.headline}}
    </div>
    
    0 讨论(0)
  • 2021-01-02 07:36

    Assume the model value is return from a $http request.

    In the controller you have 3 functions:

    function getGameContentSuccessCallback(){
       doSuccessCallback();
    }
    
    function getGameContentErrorCallback(){
      doSth()
    }
    
    function getGameContent(){
      GameContentService.GetGameContent(submitData,getGameContentSuccessCallback,getGameContentErrorCallback)
    
    }
    

    then you define doSuccessCallback in jQuery

    var doSuccessCallback = function(){   
       var country  = angular.element("#headline-game").scope().gameContent.headline;   
       alert(country );   
    }
    
    0 讨论(0)
  • 2021-01-02 07:49

    Try this

    var country = $("#headline-game").scope().gameContent.headline;
    alert(country);
    
    0 讨论(0)
提交回复
热议问题