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

时间:2015-02-20 06:53:43

标签: javascript angularjs service angularjs-scope

我为您创建了一个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;
});

提前致谢。

1 个答案:

答案 0 :(得分:1)

这里的问题是你将字符串传递给你的服务功能。字符串取消装箱,作为参考类型传递。

尝试将images对象传入您的服务功能。这应该有用。

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