最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript add event listener not working with angularjs $scope - Stack Overflow

programmeradmin3浏览0评论

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..

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..

Share Improve this question asked Sep 16, 2015 at 19:32 Gaurav GuptaGaurav Gupta 1,9255 gold badges22 silver badges40 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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>
发布评论

评论列表(0)

  1. 暂无评论