【问题标题】:angular js: accessing $scope from jQueryangular js:从 jQuery 访问 $scope
【发布时间】:2014-02-19 10:00:22
【问题描述】:

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

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

jQuery:

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

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

【问题讨论】:

  • jQuery 没有scope() 函数。

标签: javascript jquery angularjs


【解决方案1】:

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

所以你可以这样做:

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

【讨论】:

  • 我以前也这样做过。得到一个错误说:TypeError:无法读取未定义的属性“标题”
  • 你有游戏内容对象吗?在控制台上尝试这个 angular.element("#headline-game").scope() 并检查可用属性
  • @hjgrace 是的,我愿意。我试过了。但可能是因为我在 $scope 加载后在控制台中尝试过。并且在加载之前调用了jquery函数。你有办法解决吗?
  • @catwoman 一种方法是中断执行,在 chrome 控制台中使用断点或编写“调试器;” (不带引号)在控制器上设置 gameContent 变量后,它会中断执行,然后您可以在控制台中检查您的范围。
  • @ishwr 在这种情况下使用元素上的 ng-if 确保 $scope 已加载。
【解决方案2】:

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

  1. jQuery
  2. AngularJS

因此,在文档加载时在 jQuery 脚本中访问 scope() 将导致未定义,因为 jQuery 是在 before Angular 运行的。

解决这个问题的方法是让 AngularJS 在 jQuery 准备就绪后执行它,使用 directives

例子:

控制器

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>

【讨论】:

  • 对我有用的是:app.directive("myDirective", function() { return { restrict: "A", scope: { customheadline: "@" }, link: function(scope , elem, attrs) { var country = element.scope().customheadline; alert(country); } } });
【解决方案3】:

试试这个

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

【讨论】:

  • 我做到了,但由于 scope().gameContent 未定义,我收到一条错误消息:TypeError: Cannot read property 'headline' of undefined
  • 所以我认为您正在尝试在它定义之前访问它。
  • 你是对的。也许我试图在它定义之前访问它,即使我把它写在 $(function () {}) 里面那么正确的方法是什么?
  • 您需要在 Angular 中使用该 jquery 代码段,例如在 $scope.$watch("gameContent.headline") 中,以确保您拥有适当的范围和价值。
【解决方案4】:

假设模型值是从 $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 );   
}

【讨论】:

    猜你喜欢
    • 2017-11-29
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    相关资源
    最近更新 更多