1

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.

1
  • How do you know if it being called? Did you place a breakpoint? I suspect that it is called, but alert is in window scope, which is not available by default. Commented Nov 2, 2015 at 22:44

3 Answers 3

2

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
  }
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of var ShowDetail, try using $scope.ShowDetail.

Comments

0

As Amar mentioned, use $scope.ShowDetail instead of var and add event.preventDefault () inside the function to make sure href doesnt fire.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.