在 angularjs 中使用自定义服务交换 ng-src 属性

Swapping ng-src attribute using custom service in angularjs

我为您创建了一个 Pluker 以使其更容易。我可以通过将其写入控制器来使图像正常交换。我想知道如何利用自定义服务或工厂来实现相同的功能。这是代码。
HTML

<body ng-app="myApp">
    <!-- navigation bar -->
    <div id="navBar">
        <!-- here goes the dynamic navbar -->
    </div>
    <!-- navigation bar ends here -->
    <div class="row fullWidth">
        <!-- sidebar begins -->
        <div id="sidebar" ng-controller="SideCtrl">
            <!-- here goes a static sidebar -->
            <div class="large_3_custom columns">
                <ul class="side-nav side_nav_custom">
                    <li>
                        <img src="images/dashboard.png" alt="">
                        <a href="#">DASHBOARD</a>
                    </li>
                    <li>
                        <img src="images/company_profile.png" alt="">
                        <a href="#">COMPANY PROFILE</a>
                        <img ng-click="myData.swapHere();subSec = !subSec" id="arrowRotate" ng-src="{{myData.images.current}}">
                    </li>
                    <li ng-show="subSec">
                        <img src="" alt="">
                        <a href="#">SERVICES</a>
                    </li>(more on plunker)  

Angular

var myApp = angular.module("myApp", []);
myApp.service("ReverseService", function() {
    // service func goes here --
    this.imgSwap = function(a, b, def) {
        if (def === a) {
            def = b;
        } else if (def === b) {
            def = a;
        }
    }
})
myApp.controller("SideCtrl", function($scope, ReverseService) {
    console.log("thomas");
    $scope.myData = {};
    $scope.myData.images = {
        initialImage: "images/prof_arrow1.png",
        finalImage: "images/prof_arrow.png",
        current: "images/prof_arrow1.png"
    };
    $scope.myData.swapHere = function() {
        ReverseService.imgSwap($scope.myData.images.initialImage, $scope.myData.images.finalImage, $scope.myData.images.current);
    };
    $scope.subsec = false;
    $scope.bookSec = false;
});

提前致谢。

这里的问题是您将字符串传递到您的服务函数中。字符串被拆箱并且 not 作为引用类型传递。

尝试将图像对象传递到您的服务函数中。那应该可以。

myApp.service("ReverseService", function() {
    // service func goes here --
    this.imgSwap = function(images) {
        if (images.current === images.initial) {
            images.current = images.final;
        } else if (images.current === images.final) {
            images.current = images.initial;
        }
    }
})