Why does onclick="window.history.back()"
work and angular's ng-click="window.history.back()"
doesn't?
Introduction to AngularJs onclick AngularJS ng-click is an In-Built AngularJS directive that is mainly used to handle the click events on the HTML view and processing the data in the controller as per requirements. The ng-click directive can be used with multiple HTML elements such as button, input, select, checkbox, etc.
This is an example of using the ng-click directive with a button HTML element; whenever the button is clicked in HTML view, then addProduct function will get executed <img ng-src=" { {imgSrc}}" ng-style="imgSTyle" ng-click="displayDetails ()"/>
Let’s add changes in the Angular component. In Html template component- app.component.html: Added click event to a button with event binding syntax i.e bracket () symbol the event name is the name of the function placed inside the bracket. This function is called when the button is clicked.
In Angular application, displaying button code is placed in HTML template page i.e view. The trigger event is placed in the typescript component class. So user event information will be passed from view to component class.
You can make this work adding window
to your $scope
, or even better to $rootScope
so every $scope
has access to window
and thus your initial attemp would work as you've expected.
Example adding it to $rootScope
:
<script>
app.run(['$rootScope', function($rootScope) {
$rootScope.window = window
}])
</script>
Then you just call:
<button type="button" ng-click="window.history.back()">Go back</button>
or:
<button type="button" ng-click="window.alert('it works!')">Alert!</button>
or whatever variable or function in global javascript scope you want.
onclick is an javascript event, so it can call function in javascript window object.
Where as
ng-click is an angular directive, which can only call functions which is available in the $scope. window is not available in $scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With