angularjs - Angular指令可以编译ng-click元素吗

标签 angularjs angularjs-directive angularjs-compile

我写了一个指令来渲染带有 ng-click 指令的子元素,这是我的代码:

指令

angular.module('myApp')
  .directive('popover', [
    '$compile',
    function($compile) {
      return {
        scope: {
          items: "=",
        },
        link: function($scope, $element, $attrs){
          $.each($scope.items, function(key, value) {
            var item = '<a ng-click="'+value.ngClick+'">'+value.name+'</a>';
            $element.append($compile(item)($scope));
          });
        }
      }
    }
  ]
);

模板

<div popover items="myItems"></div>

Controller

angular.module('myApp')
  .controller('MyCtrl', [
    '$scope',
    function ($scope) {

      $scope.myItems = [
        {name: 'Do this', ngClick: 'doThis()' },
        {name: 'Do that', ngClick: 'doThat()' },
      ];

      $scope.doThis = function() { console.log('this is done') };
      $scope.doThat = function() { console.log('that is done') };

    }
  ]
);

渲染工作正常,我得到了一个具有正确属性的 A 元素的列表 ng-click,但是函数 doThis() 和 doThat() 永远不会被触发

我想问题出在 $compile 命令附近,但我已经在其他上下文中使用过这个命令,而且它似乎以这种方式工作得很好。此外,在 Chrome 开发工具栏中,我没有看到与元素的 ng-click 指令相关的事件。

有什么想法吗? 谢谢

最佳答案

你的指令有一个独立的作用域,所以 doThis 和 doThat 不是指令的作用域。要么删除隔离作用域,要么像这样传递函数:

app.controller('MainCtrl', function($scope) {
  $scope.myItems = [
        {name: 'Do this', ngClick: doThis },
        {name: 'Do that', ngClick: doThat },
      ];

      function doThis() { console.log('this is done') };
      function doThat() { console.log('that is done') };
});

app
  .directive('popover', function($compile) {
      return {
        scope: {
          items: "=",
        },
        link: function($scope, $element, $attrs){
          $scope.clickFunctions = {};
          $.each($scope.items, function(key, value) {
            $scope.clickFunctions[value.name] = value.ngClick
            var item = '<a ng-click="clickFunctions[\''+value.name+'\']()">'+value.name+'</a>';
            $element.append($compile(item)($scope));
          });
        }
      }
    }
);

参见 this plunker用于演示。

关于angularjs - Angular指令可以编译ng-click元素吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36933997/

相关文章:

javascript - AngularJS ng-bind-html

javascript - Angular.js 指令与加载数据的两种方式绑定(bind)

javascript - AngularJS : Compile directives inside HTML returned by an API

javascript - 在 Angular 中编译动态生成的按钮

javascript - AngularJS : invoking optional nested directive on template sub-element

javascript - 在 Protractor 测试中获取和使用属性

html - 如何使用 `Animate.css`到 `angular`的app?

javascript - 将 javascript 变量导入为常量 Angular

javascript - AngularJS 指令不显示数据

javascript - 如何创建一个使用 ng-model 的 Angular 日期选择器指令