javascript - 如何在编译后的函数中追加元素 - AngularJS

标签 javascript jquery angularjs

所以,这是我的问题。我有两个指令(例如父指令和子指令),并且我从父指令调用子指令,如下所示:

angular.module('components', [])
  .directive('helloWorld', function() {
     return {
         restrict: 'E',
         compile: function(element, attrs) {
              var x = '<directive2></directive2>';
              element.append(x);
         }
     }
   })
  .directive("directive2", function($compile, $parse) {
      return {
        restrict: 'E',
        compile: function(iElement, iAttrs, transclude) {
            iElement.append('<p>directive2</p>');
        }
      }
  });

angular.module('HelloApp', ['components'])

这很好用。但现在我在编译的后置函数中编写一个条件,当该条件满足时,应该附加子指令。

我刚刚在 post 函数中添加了追加函数,但它不起作用。

angular.module('components', [])
 .directive('helloWorld', function() {
  return {
    restrict: 'E',
    compile: function(element, attrs) {
      return {
        post: function(scope, element, attrs) {
        var x = '<directive2></directive2>';
        element.append(x);
      }
     }
   }
  }
})
.directive("directive2", function($compile, $parse) {
return {
  restrict: 'E',
  compile: function(iElement, iAttrs, transclude) {
    iElement.append('<p>directive2</p>');
   }
  }
});

angular.module('HelloApp', ['components'])

我不知道出了什么问题。 friend 们指导一下

jsFiddle

最佳答案

在附加之前,您需要使用 $compile 服务,如下所示:

angular.module('components', [])
  .directive('helloWorld', function($compile){
    return {
      restrict: 'E',
      link: function(scope, element, attrs) {
        var x = angular.element('<directive2></directive2>');
        element.append($compile(x)(scope));
      }
    }
  })
  .directive("directive2", function() {
    return {
      restrict: 'E',
      compile: function(element, attrs, transclude) {
        element.append('<p>directive2</p>');
      }
    }
  });

angular.module('HelloApp', ['components']);

http://jsfiddle.net/2zbabkjb/2/

关于javascript - 如何在编译后的函数中追加元素 - AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37118890/

相关文章:

javascript - 无法访问 Jasmine 测试用例中的范围变量

mysql - 在 AngularJS 和数据库之间保持唯一标识符同步的最佳方法是什么?

javascript - javascript 中的 JSESSIONID - Open Layers 3 如何获取它?

javascript - putFile 不是函数

javascript - 将 JavaScript 日期发送到 PHP 后端的最佳格式是什么?

javascript - 我如何调整此 javascript 以使其工作并响应?

jquery - 如何仅在 Javascript/jQuery 中获取 CSS 覆盖属性

javascript - 单击 :hover of the burger menu? 时如何制作全页宽度下拉菜单

angularjs - 使用 ngRoute 进行 Angular 路由不适用于某些路由

javascript - 双线性缩放算法奇怪的效果