2015-04-20 159 views
0

我有一个控制器,使用AJAX调用为我填充一些数据。这个调用接收一个包含其中的文字指令的字符串,以及其他一些文本。我想解析收到的字符串,以便它实际上创建所需的指令,但我绝对没有运气。指令将驻留在一个表中,所以我对执行任何类型的DOM操作以使其工作有点谨慎。从角度控制器创建指令

下面是当前没有工作这种情况下一个简单的例子:http://plnkr.co/edit/RM5FrUxAP1VVF55vSzK7?p=preview

angular.module('docsIsolateScopeDirective', []) 
    .controller('Controller', ['$scope', '$parse', 
     function($scope, $parse) { 
     $scope.data="A" 
     $scope.mydir = $parse('<my-dir info=data></my-dir>'); 
     } 
    ]) 
    .directive('myDir', function() { 
     return { 
     restrict: 'E', 
     scope: { 
      info: '=' 
     }, 
     template: '{{info}}' 
     }; 
    }); 

如果有一个更好的方式去了解它,我也很高兴听到这个消息。

谢谢!

回答

0

你必须使用$编译实现这一目标。这里是plnkr,看看这有助于

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

.directive('dynamicDirective', function($compile) { 
    return { 
    restrict: 'E', 
    replace: true, 
    scope:{ 
    content:'=' 
    }, 
    link: function (scope, ele, attrs) { 
    scope.$watch('content', function(html) { 
    ele.append($compile(html)(scope.$parent)); 
    }); 
} 
0

你可以试试这个:

... 
.directive('myDir', function ($sce) { 
    return { 
     restrict: 'E', 
     template: '<div ng-bind-html="$sce.trustAsHtml(info)"></div>', 
     scope: { info: '=' }, 
     link: function (scope) { 
      scope.$sce = $sce; 
     } 
    }; 
}); 
+0

感谢您的答复!我如何从控制器调用这个? – MegaFather

+0

请不要在控制器中使用指令,而是在模板中使用指令,如下所示:' html string'“>' – yibuyisheng

+0

我从ajax调用中取出文本,不过,很难从模板中传入。 – MegaFather