0

这是我的 AngularJS 应用程序的一部分

  .controller('Littlebear',function($scope) {
        $scope.spread='<h1>this is the</h1> Littlebear spread.'+
        '<img ng-src="src/images/retro.png" alt="picture" ng-click="click()">';
    })
   .directive('spread', function($compile) {
     var templateTemp='<p> try again </p>';
      var directive = {};


      directive.compile = function(element, attributes) {

   var linkFunction = function($scope, element, atttributes) {
       // bind element to data in $scope
       templateTemp=$scope.spread;
       return templateTemp;
   };

   return linkFunction;
   };

directive.restrict = 'E'; /* restrict this directive to elements */
directive.template = templateTemp;
return directive;
    })

我想在目录中设置 template = $scope.spread 。

如果我 console.log 链接函数内的 templateTemp,则 templateTemp 的值正是我正在寻找的,但该函数之外是 templateTemp='

再试一次

';

任何人都可以提出任何解决方案吗?

(PS:正如你想象的那样,我对 AngularJS 很陌生)

谢谢文森特

4

1 回答 1

0

在链接功能中,您可以执行以下操作。在链接功能中,我已经编译了所需的 html 并将指令元素替换为相同的元素。

.controller('Littlebear',function($scope) {
        $scope.spread='<h1>this is the</h1> Littlebear spread.'+
        '<img ng-src="src/images/retro.png" alt="picture" ng-click="click()">';
    })
   .directive('spread', function($compile) {
     var templateTemp='<p> try again </p>';
      var directive = {};


      directive.compile = function(element, attributes) {

   var linkFunction = function($scope, element, atttributes) {

				// you can change and compile the html like this
				//element.replaceWith($compile($scope.spread)); //Please Check this line<-----

//Please try this.
 var html =$scope.spread;
        var e =$compile(html)($scope);
        element.replaceWith(e);
				
   };

   return linkFunction;
   };

directive.restrict = 'E'; /* restrict this directive to elements */
directive.template = templateTemp;
return directive;
    })

于 2016-02-06T20:02:05.913 回答