【问题标题】:Angularjs directive template = $scope.(some variable from another controller)Angularjs 指令模板 = $scope.(来自另一个控制器的一些变量)
【发布时间】:2016-05-16 16:48:40
【问题描述】:

这是我的 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。

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

再试一次

';

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

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

谢谢文森特

【问题讨论】:

    标签: angularjs angularjs-controller angular2-directives


    【解决方案1】:

    在链接功能中,您可以执行以下操作。 在链接功能中,我已经编译了所需的 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;
        })

    【讨论】:

    • 感谢您的回复,我试过了,但我收到此错误“Node.replaceChild 的参数 1 不是对象。”
    • 我已经编辑了答案。检查下面给出的代码注释“//请试试这个。” $compile 需要第二个函数中的范围来针对给定范围执行绑定表达式,例如 $compile(html)($scope) 。我认为这是错误的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多