创建自定义元素指令

时间:2016-03-24 17:48:36

标签: angularjs angularjs-directive

在下面的代码中,

<!DOCTYPE html>
<html ng-app="app11" ng-cloak>
    <head>
        <title>Custom directives</title>
        <style>
            [ng\:cloak], [ng-cloak], .ng-cloak{
                display: none;
            }
        </style>
    </head>
    <body>
        <div ng-controller="mainCtrl">
            <player id="barryBonds"></player>
        </div>

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

---------------------

    var app11 = angular.module("app11", []);


    app11.directive("player", DirectiveFunction);

    function DirectiveFunction(){
        var directive = {};
        directive.restrict = 'E';
        directive.template = "{{player.name}} had a {{player.avg}} AVG with {{player.hr}} homeruns and a {{player.obp}} OBP";
        directive.scope = {player: "=name"};
        directive.compile = function(element, attributes){
            var linkFunc = function($scope, element, attributes){
                element.bind('click', function(){
                    element.html('Barry disappeared');
                });
            }
            return linkFunc;
        }
        return directive;
    }

    app11.controller("mainCtrl", MainController);

    function MainController($scope){
        $scope.barryBonds = {name: "Barry Bonds", avg: 0.298, hr: 762, obp: 0.444};
        $scope.hankAaron = {name: "Hank Aaron", avg: 0.305, hr: 755, obp: 0.374};
        $scope.babeRuth = {name: "Babe Ruth", avg: 0.342, hr: 714, obp: 0.474};
        $scope.tedWilliams = {name: "Ted Williams", avg: 0.344, hr: 521, obp: 0.482};
    }

自定义元素指令(player)的模板无法正确呈现。

实际输出为:had a AVG with homeruns and a OBP

请帮帮我!!!

1 个答案:

答案 0 :(得分:1)

下面

directive.scope = {player: "=name"};

你定义播放器应该被传递给指令的 name 属性所取代,但是你在html中传递了 id中的范围变量属性。 错误的代码:

<player id="barryBonds"></player>

修复:

<player name="barryBonds"></player>

希望它能解决你的问题