javascriptjavaangularjs

Why using anchor's ng-click is also calling a post()?


We are using AngularJS to do like/unlike behavior for our app.

Code for HTML:

<html>
  <body ng-app="myApp">
    <div ng-controller="newsCntrl" >
      <form ng-submit="post()" name="postForm" id="postForm" >
        <input type="submit" id="submit" value="Submit"/>
      </form> 
      <a href="#" ng-click="likePost(post.id);">Like</a></span>
    </div>
  </body>
</html>

Code for the controller:

myApp.controller("newsFeedCtrl", function ($scope, $http) {       
   console.log("inside newsFeedCtrl"); 

  $scope.post() = function() {  
    console.log("posting");
  }
  $scope.likePost = function(postId) { 
    console.log("liking post");
  }

});

The problem is, when we click on like, it also calls post() function, that should not be happening.

Are we missing anything here?


Solution

  • There is a mismatch between the controller name in the HTML:

      <div ng-controller="newsCntrl" >
    

    and the controller in the JS:

      myApp.controller("newsFeedCtrl", function ($scope, $http)
    

    If I fix it, it seems to work. Check this fiddle