【问题标题】:Call function in scope from directive generated html?从指令生成的html调用范围内的函数?
【发布时间】:2014-08-07 06:57:52
【问题描述】:

我已经制定了一个指令,它使用 element.html() 来设置 html。在该 html 代码中,我希望能够在使用该指令的范围内调用函数。像这样:

app.directive('myDirective', ['$rootScope', function ($rootScope) {
    return {
        restrict: 'A',
        link: function(scope, element) {
          element.html('<button ng-click="doit()">Does not work</button>');
        }
    };
}]);

doit() 函数永远不会被调用。

我做了一个 plnkr 来演示一下:

http://plnkr.co/edit/nckqny1FNiJJjthmlSh8?p=preview

【问题讨论】:

    标签: javascript html angularjs


    【解决方案1】:

    当您动态添加 HTML 时,您必须使用 $compile 服务手动编译和链接它:

    app.directive('myDirective', ['$compile', function ($compile) {
        return {
            restrict: 'A',
            link: function(scope, element) {
              var e = angular.element('<button ng-click="doit()">Works Now!!</button>');
              element.append(e);
              $compile(e)(scope);
            }
        };
    }]);
    

    【讨论】:

      【解决方案2】:

      为什么不只是一个模板?

      return {
          restrict: 'A',
          template:'<button ng-click="doit()">Do It</button>',
          link: function(scope, element, attrs) {
      
          }
      };
      

      【讨论】:

      • 这就是我要发布的内容。这是使用template:""的正确方法
      • 很可能,该代码只是一个示例。 HTML 是“在 rumtime”动态确定的。
      【解决方案3】:

      另一种方法是这样的:

      return {
        restrict: 'A',
        template: '<button>Brings up alert</button><br><button>Does not work</button>',
        link:function(scope, element, attrs){
          element.on('click', function(e){
            if(e.target.nodeName.toLowerCase() == 'button'){
              scope.doit();
            }
          });
        }
      };
      

      您可以像上面那样在链接函数中绑定事件,而不是像在代码示例中那样内联绑定点击事件,但您需要这样做:

      1. 在指令的返回中使用template:"" 选项。
      2. 在链接函数中绑定事件。
      3. 当前元素是 div 本身,但您必须在函数 args 中传递事件。
      4. 检查点击的目标是否为带有e.target.nodeName的按钮
      5. e.target.nodeName 导致 tagName 为大写,因此在上面的 if 条件中使用。
      6. 如果点击的元素是button,执行scope.doit();

      【讨论】:

      • -1 你猜怎么着,已经有一个指令。怎么又叫了……哦,对了……是ngClick
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多