In the below code.
<!DOCTYPE html>
<html ng-app="app10" ng-cloak>
<head>
<title>Custom directives</title>
<style>
[ng\:cloak], [ng-cloak], .ng-cloak{
display: none;
}
</style>
</head>
<body>
<div ng-controller="mainCtrl as o">
<div bb-player-list="bbPlayers" array-item="name | uppercase" ng-model="o">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script type="text/javascript" src="js/exam10.js"></script>
</body>
</html>
var app10 = angular.module("app10", []);
app10.directive("bbPlayerList", DirectiveFunction);
function DirectiveFunction(){
return function(scope, element, attrs){
var data = "";
if(attrs["ngModel"] === "")
data = scope[attrs["bbPlayerList"]];
else
data = scope[attrs["ngModel"]][attrs["bbPlayerList"]];
}
}
app10.controller("mainCtrl", MainController);
function MainController(){
this.bbPlayers = [
{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}
];
}
In DirectiveFunction
, there is a code smell in retrieving the data using ngModel
,
var data = "";
if(attrs["ngModel"] === "")
data = scope[attrs["bbPlayerList"]];
else
data = scope[attrs["ngModel"]][attrs["bbPlayerList"]];
Reason to add this code smell is,
if controller is instantiated like mainCtrl as o
then ngModel
would be "o"
otherwise ngModel
will be ""
. This attribute ngModel
will decide, how to access bbPlayers
in DirectiveFunction
?
Can I avoid this code smell in DirectiveFunction
?
How does DirectiveFunction
get immune to, the way mainCtrl
is instantiated?