簡體   English   中英

AngularJS指令不是渲染模板

[英]AngularJS Directive isn't rendering template

我的觀點很簡單:

<job-template ng-if="job"></job-template>

我的指令:

.directive('jobTemplate', function(){
  return {
    restrict: 'AE',
    replace: true,
    link: function(scope,element, attrs) {
        var JobStatus = scope.job.JobStatus;
        var text = "<p>"; 

        if(JobStatus === 'Created'){
          text += "{{job.id}} was created."
        }

        else if(JobStatus === 'Processing'){
          text += "{{job.id}} is currently processing."
        }

        text += "</p>";
        console.log("text");
        console.log(text);
        return text;
    }
  };

})

當我運行頁面時,我的<job-template>元素不會被替換為任何東西-盡管正確的text已加載到控制台。

我在這里做錯了什么?

link函數並不是要用於您想的那樣返回HTML,而是將作用域鏈接到指令元素時,它基本上是為了提供對角度編譯DOM的控制而存在的。 您可以在指令中使用html over template/templateUrl選項。 使用ng-if獲取條件元素。

指示

.directive('jobTemplate', function() {
  return {
    restrict: 'AE',
    replace: true,
    template: '<p>'+
        '<span ng-if="job.JobStatus == \'Created\'">{{job.id}} was created.</span>'+
        '<span ng-if="job.JobStatus == \'Processing\'">{{job.id}} is currently processing.</span>'+
      '</p>',
    link: function(scope, element, attrs) {}
  };

})

在這里演示

試試這個代碼https://plnkr.co/edit/cpdAqWN0SeUx5Gy9CQkR?p=preview

app.directive('jobTemplate', function($compile){
  return {
restrict: 'AE',
replace: true,
link: function(scope,element, attrs) {
  console.log(element)
    var JobStatus = scope.job.JobStatus;
    var text = "<p>"; 

    if(JobStatus === 'Created'){
      text += "{{job.id}} was created."
    }

    else if(JobStatus === 'Processing'){
      text += "{{job.id}} is currently processing."
    }

    text += "</p>";
    element.html(text);
    $compile(element.contents())(scope);
 }
};
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM