2015-04-20 73 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