joy
joy

Reputation: 3707

Angularjs 1.4.4 and ng-click is not working for button part of ng-repeat and its inside the directive

I am using Angularjs 1.4.4 and somehow ng-click is not working for button. button is part of ng-repeat and its inside the directive. Please use plnkr code for reference

Following is code details Directive js:

app.directive("accordion", [function() {
  return {
    restrict: "E",
    scope: {
      cities: '='
    },
    templateUrl: "Accordion.html",
    replace: true,
    link: function($scope, element, attrs) {

      $scope.clickToGetCityName = function(name) {
        alert("Welcome to city " + name);
      };


    }
  };
}]);

Directive html:

 <div data-ng-repeat="city in cities">
    <div>
        <button  data-ng-click="clickToGetCityName(city.name)" data-ng-bind-template="{{city.name}}"></button>       
    </div>
</div>

Controller Code:

var app = angular.module("Test", ['ngResource', 'ngRoute', "ngSanitize", "ngAnimate"]);
app.controller('CityViewController', ['$scope', function($scope) {

  $scope.cities = [{
    "name": "Hackansack"
  }, {
    "name": "Phoenix"
  }, {
    "name": "New York City"
  }, {
    "name": "Tempe"
  }];

}]);

index.html code:

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css">
  <!-- Angular JS  -->
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-resource.min.js"></script>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.min.js"></script>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-sanitize.min.js"></script>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-animate.min.js"></script>

  <script src="script.js"></script>
</head>

<body data-ng-app="Test" data-ng-controller="CityViewController">
  <h1>City View!</h1>
  <accordion data-cities="cities"></accordion>
</body>

</html>

Please note; I kept all the angularjs files becuase this problem I am facing in my project and i am using these all angularjs modules.

Please help.

Upvotes: 0

Views: 413

Answers (1)

michelem
michelem

Reputation: 14590

You need to remove the replace: true so your directive should be:

app.directive("accordion", [function() {
  return {
    restrict: "E",
    scope: {
      cities: '='
    },
    templateUrl: "Accordion.html",
    link: function($scope, element, attrs) {

      $scope.clickToGetCityName = function(name) {
        alert("Welcome to city " + name);
      };
    }
  };
}]);

Upvotes: 2

Related Questions