2013-05-28 55 views
29

我已经创建了下面的角度指令内,ChildDirective,用于内部ParentDirective使用的角度指令在另一指令

var wizardModule = angular.module('Wizard', []); 

wizardModule.directive('childDirective', function ($http, $templateCache, $compile, $parse) { 
return { 
    restrict: 'E', 
    scope: [], 
    compile: function (iElement, iAttrs, transclude) { 
     iElement.append('child directive<br />'); 
    } 
} 
}) 

wizardModule.directive('parentDirective', function ($http, $compile) { 
return { 
    restrict: 'E', 
    compile: function (element, attrs) { 
     var x = '<child-directive></child-directive><child-directive></child-directive>'; 
     element.append(x); 
    } 
} 

这是正常的工作和几个孩子出现的指令。

我想更新ParentDirective,得到的childDirectives从服务器列表。因此,我更新了ParentDirective代码做一个Ajax调用,然后绘制ChildDirectives

var elem; 
wizardModule.directive('parentDirective', function ($http, $compile) { 
return { 
    restrict: 'E', 
    compile: function (element, attrs) { 
     var controllerurl = attrs.controllerurl; 
     elem = element; 

     if (controllerurl) { 
      $http.get(controllerurl + '/GetWizardItems'). 
      success(function (data, status, headers, config) { 
       var x = '<child-directive></child-directive><child-directive></child-directive>'; 
       elem.append(x); 
       $compile(x); 
      }); 
     } 
    } 
} 
}); 

的问题是,childDirectives没有出现任何更多的,虽然在debeggur它正在进入到编译方法childDirective

回答

34

您必须将编译的元素链接到作用域。由于您不再修改模板元素,因此应该将新元素附加到链接元素。 YOu可以这样做:

var elem; 
wizardModule.directive('parentDirective', function ($http, $compile) { 
return { 
    restrict: 'E', 
    compile: function (element, attrs) { 
     var controllerurl = attrs.controllerurl; 
     elem = element; 

     if (controllerurl) { 
      return function(scope,element){ 
      $http.get(controllerurl + '/GetWizardItems'). 
      success(function (data, status, headers, config) { 
       var x = angular.element('<child-directive></child-directive><child-directive></child-directive>'); 
       element.append(x); 
       $compile(x)(scope); 
      }); 
      } 
     } 
    } 
} 
}); 
+1

谢谢你的帮助。我试过了,但不幸的是它没有奏效。 –

+1

我做了一个小修改,认为它应该工作var x = ** angular.element(**''** )**; – joakimbl

+0

angular.element(),解决了这个问题。并且不需要将其链接到范围。 so $ compile(x)就足够了。 Coooool –