我正在尝试在Angular中构建一个基本项目。我想根据data-ng-class中调用的函数返回的值为列表项着色。
这是我的部分html文件。
<div>
Rooms:<ul style="list-style:none;">
<li style="display:inline-block; padding:20px;"
data-ng-repeat="room in SingleDetailedCtrl.singleRooms"
data-ng-class="getClass('room')">
{{ room }}
</li>
</ul>
To go back <a ui-sref="plan">click here</a>
</div>
相应的控制器:
myApp.controller("SingleDetailedController", function ($log) {
var singleSelf = this;
this.singleRooms = ["f1-101", "f1-110", "f2-203", "f3-321", "f3-302"];
this.sa = ["f1-101", "f2-203", "f3-302"];
this.sna = ["f1-110", "f3-321"];
this.getClass = function (room) {
console.log("sdc");
var color = red;
angular.forEach(singleSelf.singleRooms, function (value, key) {
if (value == room) {
console.log("sdc if");
color = green;
}
});
return color;
};
});
我期待的控制台输出没有生成。所以,这就是我理解getClass()
函数没有被调用的方式。
我看过同样问题的不同问题。我的代码对我来说似乎不错,但它无效。
我非常感谢您解决此问题的任何帮助。
答案 0 :(得分:1)
您需要使用控制器实例,即SingleDetailedCtrl
方法
<li style="display:inline-block; padding:20px;"
data-ng-repeat="room in SingleDetailedCtrl.singleRooms"
data-ng-class="SingleDetailedCtrl.getClass('room')">
{{ room }}
</li>
答案 1 :(得分:0)
一些小错误
以下是工作代码。 (请原谅我将所有内容添加到$ scope。传递控制器实例并没有意义)
angular.module("app", [])
.controller("SingleDetailedController", function($log, $scope) {
var singleSelf = this;
$scope.singleRooms = ["f1-101", "f1-110", "f2-203", "f3-321", "f3-302"];
$scope.sa = ["f1-101", "f2-203", "f3-302"];
$scope.sna = ["f1-110", "f3-321"];
$scope.getClass = function(room) {
console.log("sdc");
var color = "red";
angular.forEach($scope.sna, function(value, key) {
if (value == room) {
color = "green";
}
});
return color;
};
});
.red{
background-color: red;
}
.green{
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="SingleDetailedController">
Rooms:
<ul style="list-style:none;">
<li style="display:inline-block; padding:20px;" data-ng-repeat="room in singleRooms" data-ng-class="getClass(room)">
{{ room }}
</li>
</ul>
To go back <a ui-sref="plan">click here</a>
</div>