Joe Consterdine Joe Consterdine - 2 months ago 17
Javascript Question

Angular Directives Incorrect

trying to make a simple directive in Angular. Doing something wrong :)

I want to output the content in 'directive.html' into the 'app-info' directive. The code works without the directive so I'm writing the directive incorrectly.

Cheers!

HTML file

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>angular</title>
</head>
<body ng-app="angularApp">
<div ng-controller="mainController">
<ul ng-repeat="item in list">
<app-Info info="item"></app-Info>
</ul>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.slim.min.js" integrity="sha256-cRpWjoSOw5KcyIOaZNo4i6fZ9tKPhYYb6i5T9RSVJG8=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript" src="angular.js"></script>
</body>
</html>


Angular.js file

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

app.controller("mainController", ["$scope", function($scope){
$scope.list = [
{
name: "Joe",
age: 26,
job: "Front-End Developer",
skill: 0
},
{
name: "Rob",
age: 23,
job: "Ruby Developer",
skill: 0
},
{
name: "Mark",
age: 25,
job: "Back-End Developer",
skill: 0
}
];

$scope.skill = function(index) {
$scope.list[index].skill += 1;
};
}]);

app.directive("appInfo", function(){
return {
restrict: "E",
scope: {
info: "="
},
templateUrl: "directive.html"
};
});


Directive html file

<li>{{ item.name }}</li>
<li>{{ item.age | currency }}</li>
<li ng-click="skill($index)">{{ item.skill }}</li>

Answer

There were few issues i noticed in the pasted code:

Firstly, you need to modify your directive.html to use {{info.name}} instead of {{item.name}} since your directive scope variable is info and not item.

Secondly, modify your html file. Directive name should be "app-info" instead of "app-Info"

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>angular</title>
</head>
<body ng-app="angularApp">
  <div ng-controller="mainController">
    <ul ng-repeat="item in list">
         <app-info info="item"></app-info>
    </ul>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.slim.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js">  
</script>
<script type="text/javascript" src="angular.js"></script>
</body>
</html>

Directive.html

<li>{{ info.name }}</li>
<li>{{ info.age }}</li>
<li ng-click="skill($index)">{{ info.skill }}</li>

[WorkingDemo]