简体   繁体   中英

Angular js ng-click not firing for hyperlink

Im trying to learn Angular. I created a simple view as follows:

<!DOCTYPE html>
<html ng-app="MyApp">

  <head>
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="MyCtrl">
   <div>
     <table ng-repeat="d in Details">
       <tr>
         <td>{{d.Name}}</td>
         <td>{{d.Salary}}</td>
         <td><a href="#" ng-click="ShowDetail(d)">Select</a></td>
       </tr>
     </table>
   </div>

  </body>

</html>

Controller:script.js

// Code goes here

    var MyModule=angular.module("MyApp",[]);

    var MyCtrl=function($scope){

      var Details=[
        {Name:'XXXX',Salary:40000},
        {Name:'YYYY',Salary:50000},
        {Name:'ZZZZ',Salary:60000},
        {Name:'AAAA',Salary:70000}
        ];

      $scope.Details=Details;

      var ShowDetail=function(detail){
        alert("You selected "+detail.Name+"Salary is "+detail.Salary);
      };
    }
MyModule.controller("MyCtrl",MyCtrl);

Problem is when I click on the hyperlink 'Select' hyperlink I dont see any event firing. Please help.

In Angular, your controller handles the interaction with view. So any events in your view is handled by the respective controller.

The view and controller are tightly coupled to each other via $scope . Thus, any variables, objects or event handlers must be exposed on $scope in order to access them in your view.

Since you are calling, showDetail , which is defined in your controller, is still a normal JS function, and not in the context of Angular. To use the same in your view, you need to expose it through $scope .

Thus your function should be declared as follows,

 $scope.showDetail = function() {
   // your logic goes here
  }

而不是var ShowDetail ,尝试使用$scope.ShowDetail

正如Amar所​​提到的,使用$scope.ShowDetail代替var并在函数内添加event.preventDefault()以确保href不会触发。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM