angular js:从jQuery访问$ scope

时间:2014-02-19 10:00:22

标签: javascript jquery angularjs

stackoverflow中有几个这样的问题。我知道。尝试了所有的答案,但仍然没有运气。 我的HTML:

    <div class="headline" id="headline-game">
        {{gameContent.headline}}
    </div>

jQuery的:

    var country = $("#headline-game").scope().headline;
    alert(country);

但我没有定义,而是我的范围。谁能帮我?我不想改变范围,只是访问它。

4 个答案:

答案 0 :(得分:12)

Angular会在您的窗口中添加一个全局angular变量。

所以你可以这样做:

angular.element("#headline-game").scope().gameContent.headline;

答案 1 :(得分:2)

问题是由插件初始化的顺序引起的。

  1. 的jQuery
  2. AngularJS
  3. 因此,在文档加载时访问jQuery脚本中的scope()将导致未定义,因为jQuery在之前运行

    解决方案是让AngularJS在准备就绪后使用指令执行jQuery。

    示例:

    控制器

    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>
    

答案 2 :(得分:0)

试试这个

var country = $("#headline-game").scope().gameContent.headline;
alert(country);

答案 3 :(得分:0)

假设模型值是从$ http请求返回。

在控制器中你有3个功能:

function getGameContentSuccessCallback(){
   doSuccessCallback();
}

function getGameContentErrorCallback(){
  doSth()
}

function getGameContent(){
  GameContentService.GetGameContent(submitData,getGameContentSuccessCallback,getGameContentErrorCallback)

}

然后在jQuery中定义doSuccessCallback

var doSuccessCallback = function(){   
   var country  = angular.element("#headline-game").scope().gameContent.headline;   
   alert(country );   
}