2017-11-18 108 views
0

您好,我試圖從AngularJs指令中返回表並將其綁定。AngularJs指令在返回模板數據之前呈現

我的角碼是:

function directive($window, employeeDataServices) { 
    var directive = { 
     link: link, 
     restrict: 'EA', 
     renderOnFirstLoad: false, 
     template: myData() 
    }; 
    return directive; 
    function link(scope, element, attrs) { 
    } 
    function myData() { 
     angular.element(document).ready(function() { 
     employeeDataServices.getEmployees().then(function (response) { 
      var table = "<table>"; 
      table += "<tr>"; 
      table += "<th>Id</th>"; 
      table += "<th>Name</th>"; 
      table += "</tr>"; 
      angular.forEach(response, function (value, key) { 
      table += "<tr>"; 
      table += "<td>" + value.Id + "</td>"; 
      table += "<td>" + value.Name + "</td>"; 
      table += "</tr>"; 
      }); 
      table += "</table>"; 
      return table; 
     }); 
     }); 
    } 
    } 

而在HTML中我使用

<div directive></div> 

的AngularJs指令返回HTML綁定後的表

+0

是的,不,真的,這不是應該如何使用angularjs。你不明白異步。模板是純粹靜態的HTML。通過使用角度表達式,在模板內使用ng-repeat等,並綁定到數據,可以使其動態化。暫時忘記指令,只是瞭解基本的控制器和視圖。 –

回答

0

既然你正在爲請求後端(我認爲)在

employeeDataServices.getEmployees() 

您不能在指令中使用模板屬性。爲了實現您的功能,您可以使用帖子鏈接功能

function directive($window, employeeDataServices) { 
var directive = { 
    restrict: 'EA', 
    renderOnFirstLoad: false, 
    compile: function() { 
     return { 
      post: function (scope, element, attrs) { 
       employeeDataServices.getEmployees().then(function (response) { 
        var table = "<table>"; 
        table += "<tr>"; 
        table += "<th>Id</th>"; 
        table += "<th>Name</th>"; 
        table += "</tr>"; 
        angular.forEach(response, function (value, key) { 
         table += "<tr>"; 
         table += "<td>" + value.Id + "</td>"; 
         table += "<td>" + value.Name + "</td>"; 
         table += "</tr>"; 
        }); 
        table += "</table>"; 
        element.append(table); 
       }); 
      } 
     } 
    } 
}; 
return directive; 
} 

沒有時間去驗證,但你得到了要點。

+0

感謝您的回覆,它適合我。 –

+0

你能接受答案嗎? –

+0

確定我現在正在做。 –

相關問題