2

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";
    });
});

Here is my complete program: Link

I will be glad if someone help me with this.

1
  • 3
    why not use ng-click handler Commented Mar 6, 2017 at 8:20

3 Answers 3

5

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

Like this:

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

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

Here's a w3schools link to the program: Link

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";
        });
    });
});

Here's a w3schools link to the program: Link

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

better to call $scope.$apply() I'd say (sitepoint.com/understanding-angulars-apply-digest)
Please not only answer his question, but defy that he uses the .click handler instead of ng-click
0

Angular JS provides ng-click directive to handle click event.Just add ng-click=function_name() as an attribute in your HTML element.The ng-click directive tells AngularJS what to do when an HTML element is clicked.

Example

angular.module('myApp', [])
.controller('myCtrl',function($scope) {
    $scope.myFunc = function() {
        console.log('clicked');
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">

<div ng-controller="myCtrl">
    <button ng-click="myFunc()">Click</button>
</div>

Comments

0

I am not sure, why aren't you using the standard ng-click to catch the click event. Please explain if you have a specific reason for that. But if you still want to follow the Jquery way, you should invoke angular digest cycles, as soon as you change the value. Use $scope.$apply()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.