1

this is my html file:

<section data-ng-controller="myCtrl">
    {{name}}
    <button id="btn1">Button1</button>
</section>

this is my controller:

angular.module('users').controller('myCtrl', ['$scope',
    function($scope) {

        $scope.name="HELLO";

        document.getElementById("btn1").addEventListener("click",function(){
            $scope.name="changed";
        });
}]);

the html file displays HELLO but it does not changes to "changed" on clicking the button. i am new to angular can someone please help me..

1 Answer 1

4

It's because regular event listeners don't trigger a $digest cycle within Angular, which is what will update the view. You should be using ngClick and defining a $scope function:

$scope.clickHandler = function() { $scope.name = "changed"; };

And the HTML:

<button ng-click="clickHandler()">Button1</button>
Sign up to request clarification or add additional context in comments.

1 Comment

Addition: another way of solving this (because you will encounter third party code / libraries with which this solution cannot be applied) is by calling $scope.$apply(); after a variable in the $scope was updated.

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.