Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ng-click with inline function

Why does onclick="window.history.back()" work and angular's ng-click="window.history.back()" doesn't?

like image 888
Joe Avatar asked Jun 20 '16 10:06

Joe


People also ask

What is ng-click in angular?

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.

How to use ng-click directive with a button HTML element?

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 ()"/>

How to add click event to a button in angular?

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.

How to display button code in angular?

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.


2 Answers

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.

like image 165
jaacoder Avatar answered Oct 11 '22 21:10

jaacoder


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.

like image 3
John Avatar answered Oct 11 '22 23:10

John