0

In the below code,

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

The template of custom element directive(player) does not render correctly.

Actual output is: had a AVG with homeruns and a OBP

Please help me!!!

1 Answer 1

1

Here

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

you define that player should be taken by the name attribute passed to the directive, but in you html you pass the scope variable in the id attribute. Wrong code:

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

Fix:

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

Hope it solves your problem

Sign up to request clarification or add additional context in comments.

4 Comments

One supple, If controller instance is created as <div ng-controller="mainCtrl as o">, then how would you see the code changes in directive?
it would not change at all ;)
var linkFunc = function($scope, element, attributes){ remains as it is?
yes, if you notice you never refer to the controller from the directive nor viceversa. they are "communicating" through $scope

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.