Azhar Ch Azhar Ch - 3 months ago 22
AngularJS Question

angular directives not working

**Hello.html**


html code of what i want to do by making a directive

<script src="angular.min.js"></script>
<script src="world.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />

<body ng-app="myApp">

<record></record>
</body>

**world.js**


i just make a directive but it's not working can anyone please find out my errors

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

app.directive("rec",function()
{
return{
restrict:'E',
templateUrl:'record.html',
controller:function($scope) {
$scope.records = [
{
"Name" : "Alfreds Futterkiste",
"Country" : "Germany"
}, {
"Name" : "Berglunds snabbköp",
"Country" : "Sweden"
},{
"Name" : "Centro comercial Moctezuma",
"Country" : "Mexico"
},{
"Name" : "Ernst Handel",
"Country" : "Austria"
}
],controllerAs:'records'
}
};
});

**record.html**


this is a new file record.html which i made to separate my working load but chrome is not showing it . can you please find out my errors for correction

<table border="1">
<tr ng-repeat="x in records">
<td>{{x.Name}}</td>
<td>{{x.Country}}</td>
</tr>
</table>

Answer

Your controllerAs is inside controller it should be outside like below

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

app.directive("rec",function()
{
    return{
        restrict:'E',
        templateUrl:'record.html',
        controller:function($scope) {
             $scope.records = [
             {
                "Name" : "Alfreds Futterkiste",
                "Country" : "Germany"
             }, {
            "Name" : "Berglunds snabbköp",
            "Country" : "Sweden"
             },{
            "Name" : "Centro comercial Moctezuma",
            "Country" : "Mexico"
            },{
            "Name" : "Ernst Handel",
            "Country" : "Austria"
            }
           ]},
        /*this should be outside of controller*/
        controllerAs:'records'
    };
});

and your directive call in html must be directive name as

<rec></rec>

See working plunker