1

当我点击我的灯泡时,我想切换我的 2 个打开和关闭图像。有时它似乎有效,而其他时候则无效。除非我使用 ng-repeat 和至少两个图像,否则我根本无法让 ng-click 工作。我如何最好地完成切换 1 个灯泡的图像?有没有办法同步复选框,以便当它被选中时灯亮,当它关闭时灯熄灭?(我是 javascript 新手)这是小提琴: 小提琴

<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; 

    }
};
}  
4

2 回答 2

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/

于 2013-10-29T21:40:51.603 回答
1

条件有问题if。ng-repeat 适用于 JSON 对象。因此,函数参数“图像”是一个对象。正确的if说法如下:

if (image.imgUrl === $scope.offUrl) {

我已经更新了小提琴。网址是:http: //jsfiddle.net/7857c/1/

于 2013-10-29T21:46:32.103 回答