Problem when using JS events in AngularJs (Mini-Challenge 1)

Mini-challenge 1

ng-challenge

AngularJs Mini-Challenges is a growing collection of “Challenges” about the most quirky parts of the AngularJs framework. It encourage you to find and fix common mistakes and subtle bugs, as well as performance issues and bad practices, that non-expert AngularJs programmers may encounter on their endeavours into the depths of the framework.

AngularJs Mini-Challenges does not aim to teach you AngularJs. Former knowledge of the Framework is strongly recommended in order to understand the topics covered in this Challenges. In order to learn the basics of the Framework, please head over to this excellent book:

 

book

Book Tip

ng-book – The Complete Book on AngularJS
Ready to master AngularJS? What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall?


Amazon

 

 

The Challenge:

Lets suppose we have an angular app with a button, when you click that button, a text should appear in the view.
As requirement we have to handle the onclick event of the button with vanillaJs.
E.g.
document.getElementById(‘btn’).onclick = function (e) {

});

This is how the view looks like:

<div><button id="btn" type="button">Click me</button>
<div>{{name}}</div>
</div>

This is how the controller looks like:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function ($scope) {

document.getElementById('btn').onclick = function (e) {
$scope.name = "Button clicked";
}
});

Here is a jsfiddle with the code:

Notes:

Even when for this challenge you can’t use directives (see the constraint above), I strongly recommend to use directives to handling events all the time, when working with angularJs, try to avoid to use JavaScript Event handling in real life projects.
For the sake of this challenge as a constraints requirements, we can’t use the ng-click directive.
As a result, the code doesn’t work, so, the challenge is to solve it without use ng-* angular directive.

Here you can find a possible solution

If you feel that the solution is poor or incomplete or there is room for improvement, please share with every one, you can leave a comment.