如何将参数传递给Angular中的ng-event处理程序?

时间:2016-01-18 11:56:17

标签: javascript angularjs

我有一段这样的代码:

Module.Article.directive('article', function ($compile) {
 return {
    restrict: 'C',
    link: function (scope, element, attrs) {

    var el = angular.element('<div></div>');

    scope.showNum = function(i){
      console.log(i);
    };

    for (var i = 1; i <= 5; i++) {
      el.append('<span ng-mouseover="showNum(i)">' + i + '</span>');
    }

    $compile(el)(scope);
    element.append(el);
}

我希望得到这个结果:

<div>
  <span ng-mouseover="showNum(1)">1</span>
  <span ng-mouseover="showNum(2)">2</span>
  <span ng-mouseover="showNum(3)">3</span>
  <span ng-mouseover="showNum(4)">4</span>
  <span ng-mouseover="showNum(5)">5</span>
</div>

但我得到了这样的结果:

<div>
   <span ng-mouseover="showNum(i)">1</span>
   <span ng-mouseover="showNum(i)">2</span>
   <span ng-mouseover="showNum(i)">3</span>
   <span ng-mouseover="showNum(i)">4</span>
   <span ng-mouseover="showNum(i)">5</span>
</div>

有人知道如何将我传递给showNum()处理程序吗?

2 个答案:

答案 0 :(得分:1)

将其更改为此,因此实际的i变量将被打印而不是字母i:

Module.Article.directive('article', function ($compile) {
 return {
    restrict: 'C',
    link: function (scope, element, attrs) {

    var el = angular.element('<div></div>');

    scope.showNum = function(i){
      console.log(i);
    };

    for (var i = 1; i <= 5; i++) {
      el.append('<span ng-mouseover="showNum(' + i + ')">' + i + '</span>');
    }

    $compile(el)(scope);
    element.append(el);
}

编辑:我同意另一个答案提供了更大的灵活性,这个答案指出了提出问题的人试图实现它的方式中的一个小错误。

答案 1 :(得分:0)

您可以使用ng-repeat呈现template并传递值,只需要在指令链接函数中创建items数组,ng-repeat将处理渲染部分HTML。

<强>指令

Module.Article.directive('article', function($compile) {
  return {
    restrict: 'C',
    template: '<div>' +
                 '<span ng-repeat="i in items" ng-mouseover="showNum(i)">{{i}}</span>'+
              '</div>',
    link: function(scope, element, attrs) {

      var el = angular.element('<div></div>');

      scope.showNum = function(i) {
        console.log(i);
      };
      scope.items = [];
      for (var i = 1; i <= 5; i++) {
        scope.items.push(i)
      }
    }
  }
});

Demo Plunkr