Angularjs 1.4.4和ng-click不适用于ng-repeat的按钮部分及其在指令内部

时间:2015-08-23 07:04:25

标签: angularjs

我正在使用Angularjs 1.4.4并且某种方式ng-click不适用于按钮。按钮是ng-repeat的一部分,它在指令中。请使用plnkr code作为参考

以下是代码详细信息 指令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);
      };


    }
  };
}]);

指令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>

控制器代码:

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代码:

<!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>

请注意;我保留了所有的angularjs文件,因为我在项目中面临的这个问题,我正在使用这些所有angularjs模块。

请帮忙。

1 个答案:

答案 0 :(得分:2)

您需要删除replace: true,因此您的指令应为:

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);
      };
    }
  };
}]);