尝试在Angular中创建一个简单的指令。做错了什么:)
我想将'directive.html'中的内容输出到'app-info'指令中。代码在没有指令的情况下工作,所以我写错了指令。
干杯!
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" 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文件
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"
};
});
指令html文件
<li>{{ item.name }}</li>
<li>{{ item.age | currency }}</li>
<li ng-click="skill($index)">{{ item.skill }}</li>
答案 0 :(得分:1)
我在粘贴的代码中注意到的问题很少:
首先,您需要修改directive.html以使用{{info.name}}
而不是{{item.name}}
,因为您的指令范围变量是info而不是item。
其次,修改你的html文件。指令名称应为“app-info”而不是“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>
答案 1 :(得分:-1)
我认为您的指令需要包含在div标签或其他标签中。它必须有一个根元素。