我正在尝试使用ng-repeat显示列表。直接在html中使用时,它可以正常工作。但是,当我尝试使用指令插入相同的代码时,ng-repeat不执行任何操作,甚至不会显示一个项目。
我尝试了什么:
<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>
答案 0 :(得分:3)
您创建了本地变量Appraisals,因此视图无法看到它。它需要在一个范围内:
alert(Appraisals[0].id);
return {
restrict: 'E',
replace: 'true',
scope: {
Appraisals: '='
}
link: function(scope, element, attrs, tabsCtrl) {
scope.Appraisals = Appraisals;
},
template: '<div>'+