编译模板时代码有异味

时间:2016-03-25 13:09:44

标签: javascript angularjs angularjs-directive

在下面的代码中,

<!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

如何解决此代码异味?

1 个答案:

答案 0 :(得分: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.
    }
  }
});