简体   繁体   English

Angular js ng-click不会触发超链接

[英]Angular js ng-click not firing for hyperlink

Im trying to learn Angular. 我想学习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 控制器:的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. 在Angular中,您的控制器处理与视图的交互。 So any events in your view is handled by the respective controller. 因此,视图中的任何事件都由相应的控制器处理。

The view and controller are tightly coupled to each other via $scope . 视图和控制器通过$scope紧密耦合。 Thus, any variables, objects or event handlers must be exposed on $scope in order to access them in your view. 因此,必须在$scope上公开任何变量,对象或事件处理程序,以便在视图中访问它们。

Since you are calling, showDetail , which is defined in your controller, is still a normal JS function, and not in the context of Angular. 因为你正在调用,所以在你的控制器中定义的showDetail仍然是一个普通的JS函数,而不是在Angular的上下文中。 To use the same in your view, you need to expose it through $scope . 要在视图中使用相同的内容,您需要通过$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不会触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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