从jQuery设置$ scope变量的值 [英] Set value of $scope variable from jQuery

查看:644
本文介绍了从jQuery设置$ scope变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在jQuery函数中为$ scope中的变量设置一个值,如下面的代码所示。一切都很好,但新的价值反映在用户界面。

I want to set a value to a variable in $scope from jQuery function as below code. Everything is good but the new value is reflecting in UI.

app.controller('myCtrl', function($scope) {
    $scope.carname = "Volvo";

    $('#sample').click(function(e){
        $scope.carname = "Audi";
    });
});

这是我的完整程序:链接

如果有人帮我这个,我会很高兴。

I will be glad if someone help me with this.

推荐答案

为了使你的代码有效,你需要运行 $ scope。$ digest()分配 $ scope.carname =Audi;

In order to make your code work, you need to run $scope.$digest() after you assign $scope.carname = "Audi";

喜欢这样:

app.controller('myCtrl', function($scope) {
    $scope.carname = "Volvo";

    $('#sample').click(function(e){
        $scope.carname = "Audi";
        $scope.$digest();
    });
});

这是该计划的w3schools链接:链接

Here's a w3schools link to the program: Link

如下面的评论中所述,您也可以使用 $ scope。$ apply()如下所示:

As mentioned in the comments below, you can also use $scope.$apply() like the following:

app.controller('myCtrl', function($scope) {
    $scope.carname = "Volvo";

    $('#sample').click(function(e){
        $scope.$apply( function() {
            $scope.carname = "Audi";
        });
    });
});

这是该计划的w3schools链接:链接

Here's a w3schools link to the program: Link

您可以阅读有关<$的用例的更多信息c $ c> $ scope。$ digest()和 $ scope。$ apply()在以下链接中:

You can read more about the use cases for $scope.$digest() and $scope.$apply() in the following links:

  • Understanding Angular's $apply() and $digest()
  • AngularJS $watch(), $digest(), and $apply()

注意:正如许多其他评论中所述&一些答案,Angular确实提供了一个内置的方法来监听点击事件,名为 ng-click 。以下是它的文档: AngularJS:ngClick

Note: As mentioned in many other comments & some answers, Angular does provide a built-in method to listen for a click event, called ng-click. Here is the documentation for it: AngularJS: ngClick

这篇关于从jQuery设置$ scope变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆