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
。
如何解決此代碼異味?