【发布时间】:2016-08-24 09:10:39
【问题描述】:
我正在尝试使用 ng-repeat 显示列表。当直接在 html 中使用时,它可以正常工作。但是,当我尝试使用指令插入相同的代码时,ng-repeat 什么也不做,甚至不显示一项。
我尝试了什么:
- 我在 .html 和 .js 文件中使用了相同的 html - 在 html 中没有问题,在指令中没有问题
- 我添加了
<h1>Say Something</h1>只是为了检查指令是否正确应用 - 是的,是的 - 我尝试直接在指令中声明数组(值应通过范围传递)- 行为没有变化
-
alert(Appraisals[0].id)显示包含正确信息的弹出窗口 - 检查了拼写和拼写错误,但一切似乎都正确...
.js 文件:
var app = angular.module('AngularDirectiveDemo', []);
(function () {
var app = angular.module('AngularDirectiveDemo');
app.directive('scSchedule', function () {
//alert($scope.Appraisals[0]);
var Appraisals = [
{ id: 2432, name: "Greatness" },
{ id: 2486, name: "Mediocrity" }
];
alert(Appraisals[0].id);
return {
restrict: 'E',
replace: 'true',
template: '<div>'+
'<h1>Say Something Directive</h1><ul> <li ng-repeat="x in Appraisals">' +
'{{x.id}}<a href="#" ng-click="viewAppraisalDetails(x)">Details</a></li></ul><div>blanko</div></div>',
controller: function ($scope) {
$scope.viewAppraisalDetails = function (appraisalToView) {
console.log('viewing details for ' + appraisalToView.Id);
}
}
};
});
angular.module('AngularDirectiveDemo').controller('scheduleCtrl',function($scope){
$scope.Appraisals=[
{id: 2432, name:"Greatness"},
{id:2486, name:"Mediocrity"}
];
});
}());
html文件:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" ng-app="AngularDirectiveDemo">
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
<SharePoint:ScriptLink name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />
<script src="../Scripts/angular.js"></script>
<!-- <script type="text/javascript" src="../Scripts/App.js"></script> -->
<script src="../Codes/SampleDirective.js"></script>
<title>Angular Directive Demo</title>
</head>
<body>
<div ng-controller="scheduleCtrl">
<h1>Hello world</h1>
<ul>
<li ng-repeat="x in Appraisals">{{x.id}} {{x.name}}</li>
</ul>
</div>
<sc-Schedule></sc-Schedule>
</body>
</html>
【问题讨论】:
-
用
sc-schedule替换sc-Schedule -
另外,您的指令不在
<div ng-controller="scheduleCtrl">范围内,因此评估不在其范围内。 -
谢谢。第二条评论解决了这个问题。您能否将其发布为答案以便我接受?另外,为什么我在指令中声明 Appraisals 没有帮助?
-
因为它仍然不在范围内。它只是指令的一个局部变量。
标签: angularjs angularjs-ng-repeat