Reputation: 31
<html ng-app>
<head>
<script language="javascript" src="./angular-1.0.6/angular.js"></script>
<script language="javascript">
function scopeReady(s) {
document.getElementById("btn").addEventListener("click", function(event) {
alert(s.items);
s.btnClick();
alert(s.items);
});
}
function ctrl($scope) {
$scope.items = ["abc", "def", "ghi"];
$scope.btnClick = function() {
$scope.items.push("one more");
};
scopeReady($scope);
}
</script>
</head>
<body ng-controller="ctrl">
<li ng-repeat="item in items">{{item}}</li>
<button id="btn">Event Handler</button>
<button ng-click="btnClick()">Angular ngClick</button>
</body>
</html>
As what the code snippet shows, why the click of the first button does not trigger update of DOM? Both ng-click and the event handler invokes the same function to proceed. It's quiet confusing to me.
Upvotes: 2
Views: 1603
Reputation: 364707
Event handlers run "outside" of Angular, so Angular doesn't know about the change to items
, so the ng-repeat does not re-render. Call s.$apply()
to cause Angular to run a digest cycle, which will update your view.
With ng-click, scope.$apply()
is called automatically.
Upvotes: 4