我想切换我的2&当我点击我的灯泡时关闭图像。有时似乎有效,有时却没有。除非我使用ng-repeat和至少两个图像,否则我无法使用ng-click工作。如何最好地切换1个灯泡的图像?是否有任何方法可以同步复选框,以便在检查时指示灯亮起以及何时熄灭指示灯熄灭? (我是javascript的新手)这是小提琴: Fiddle
<body ng-app="myApp">
<div ng-controller="MyCtrl">
lightbulb is {{state}} <input type="checkbox" ng-model=
"state" ng-true-value="on" ng-false-value="off">
<div ng-repeat="image in images">
<a ng-click="toggleImage(image)">
<img ng-src="{{image.imgUrl}}" />
</a>
</div>
</div>
function MyCtrl($scope) {
//$scope.checkboxState = "off";
//$scope.resetUrl = 'http://www.w3schools.com/js/pic_bulboff.gif';
$scope.state = "on";
$scope.onUrl = 'http://www.w3schools.com/js/pic_bulbon.gif';
$scope.offUrl = 'http://www.w3schools.com/js/pic_bulboff.gif';
$scope.images = [
{imgUrl: 'http://www.w3schools.com/js/pic_bulboff.gif'},
{imgUrl: 'http://www.w3schools.com/js/pic_bulbon.gif'},
];
$scope.toggleImage = function (image) {
if (image === $scope.offUrl) {
image.imgUrl = $scope.onUrl;
} else {
image.imgUrl = $scope.offUrl;
}
};
}
答案 0 :(得分:2)
切换内容的最简单方法是将状态存储在范围内,然后根据该状态进行渲染。现在你有很多可以消除的无关代码。我会将您的代码重组为:
function MyCtrl($scope) {
$scope.onUrl = "pic_bulbon.gif";
$scope.offUrl = "pic_bulboff.gif";
$scope.isBulbOn = false;
$scope.bulbText = function() { return $scope.isBulbOn ? "on" : "off"; };
$scope.bulbUrl = function() {
return $scope.isBulbOn ? $scope.onUrl : $scope.offUrl;
};
}
<body ng-app="myApp">
<div ng-controller="MyCtrl">
lightbulb is {{ bulbText() }}
<input type="checkbox" ng-model="isBulbOn">
<a ng-click="isBulbOn = !isBulbOn">
<img ng-src="{{ bulbUrl() }}" />
</a>
</div>
</body>
您可以在此处查看小提琴:http://jsfiddle.net/UYaLJ/
答案 1 :(得分:1)
if
条件存在问题。 ng-repeat适用于JSON对象。因此,函数参数“image”是一个对象。正确的if
语句如下:
if (image.imgUrl === $scope.offUrl) {
我已经更新了小提琴。网址为:http://jsfiddle.net/7857c/1/