2016-03-25 78 views
1

在下面的代碼,代碼味道在編譯模板

<!DOCTYPE html> 
<html ng-app="app14" ng-cloak> 
    <head> 
     <meta charset="UTF-8"> 
     <title> Angular built-in services</title> 
     <style> 
      [ng\:cloak], [ng-cloak], .ng-cloak{ 
       display: none; 
      } 

     </style> 
    </head> 
    <body> 
      <!-- Using $angular service--> 
      <p get-player-info></p> 


     </div> 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script> 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-sanitize.js"></script> 
     <script type="text/javascript" src="js/exam14.js"></script> 
    </body> 
</html> 

var app14 = angular.module('app14', ['ngSanitize']); 

function MainController($window, $location, $interval, $log, $exceptionHandler, $sanitize){ 

    /***** For $compile service ********/ 
    this.players = [ 
     {name: "Barry Bonds", avg: 0.298, hr: 762, obp: 0.444}, 
     {name: "Hank Aaron", avg: 0.305, hr: 755, obp: 0.374}, 
     {name: "Babe Ruth", avg: 0.342, hr: 714, obp: 0.474}, 
     {name: "Ted Williams", avg: 0.344, hr: 521, obp: 0.482} 
    ]; 

} 

app14.controller('mainCtrl', MainController); 


/***** using $compile service ********/ 

app14.directive("getPlayerInfo", function($compile){ 
    return function(scope, element, attrs){ 
     var playerList ="<ul><li ng-repeat='player in o.players'>{{player.name}}</li></ul>"; 

     var listElement = angular.element(playerList); 

     var compileFunction = $compile(listElement); 
     compileFunction(scope); 

     element.append(listElement); 
    } 
}); 

有一個在getPlayerInfo指令代碼的氣味(如下圖所示)

var playerList ="<ul><li ng-repeat='player in o.players'>{{player.name}}</li></ul>"; 

我們在自定義指令中明確使用o.players

如何解決此代碼異味?

回答

0

使用指令的template選項來加載html,並使用隔離範圍並通過指令屬性=(雙向綁定)傳遞players值。在那裏你只是擺脫父控制器的控制器別名,通過將值傳遞給players指令的屬性。

標記

<p get-player-info players="o.players"></p> 

指令

app14.directive("getPlayerInfo", function($compile){ 
    return { 
    template: '<ul><li ng-repeat='player in players'>{{player.name}}</li></ul>', 
    scope: { 
     players: '=' 
    }, 
    link: function(scope, element, attrs) { 
     //do manipulate DOM from here. 
    } 
    } 
});