AngularJS指令不是渲染模板

时间:2016-03-25 07:45:11

标签: javascript angularjs angularjs-directive

我的观点很简单:

<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已加载到控制台。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:3)

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) {}
  };

})

Demo here

答案 1 :(得分:0)

试试此代码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);
 }
};
})