簡體   English   中英

如何在ng-repeat循環內分配angularjs事件偵聽器?

[英]How do I assign an angularjs event listener inside an ng-repeat loop?

我是angularjs的新手。 我正在嘗試創建一個圖片庫,其中初始頁面是一張用angularjs ng-repeat循環創建的來自twitter和instagram的縮略圖照片。 當用戶將鼠標懸停在圖像上時,圖像會褪色,並出現一個按鈕供用戶單擊。 我使用ng-mouseenter和ng-mouseleave創建了懸停效果。 但是由於某種原因,當我將鼠標懸停在圖像上時,所有圖像都會受到影響。 僅定位我懸停的單個圖片。 我不確定我做錯了什么。 請幫忙! 代碼如下。 另外,這里是在線代碼的鏈接: http : //www.petermingione.com/my-demo/

<style>
        * {
            box-sizing: border-box;
            font-family: sans-serif;
        }
        h1, 
        h2{
            margin-left:10px;
        }
        .inner{
            display:inline-block;
            vertical-align:top;
            padding:5px;
            position:relative;
        }
        .inner img{
            width:100%;
        }
        .inner .outer-caption{
            color:black;
            width:375px;
            height:125px;
            background-color:#fc7cab;
            display:flex;
        }
        .inner .outer-caption .inner-caption{
            font-size:14px;
            font-family:sans-serif;
            overflow:hidden;
            width:320px;
            height:70px;
            margin:auto;
        }
        .inner .overlay-color{
            position: absolute;
            top:0;
            bottom:0;
            left:0;
            right:0;
            margin:auto;
            background-color: #fff;
            transition: all .5s;    
        }
        .inner .overlay-text{
            border: 2px solid #7e7e7e;
            color:#7e7e7e;
            font-size: 10px;
            position: absolute;
            top:0;
            bottom:0;
            left:0;
            right:0;
            width:70px;
            height:35px;
            line-height:35px;
            margin:auto;
            border-radius:1px;
            text-align: center;
            transition: all .5s;

    </style>

<body>  
    <h1>{{title}}</h1> 
    <h2>{{myMessage}}</h2>
    <div id="outer" class="outer">
        <div class="inner" ng-mouseenter="makeVisibile()" ng-mouseleave="makeInVisibile()" ng-repeat="x in insideData">
            <img ng-if="x.service=='Instagram'||(x.service=='Twitter' && x.mediaType=='image')" ng-src='{{x.thumbnails[0].url}}'>
             <div ng-if="x.service=='Twitter'&& x.mediaType!='image'" class="outer-caption"><div class="inner-caption">{{x.caption}}</div></div>
            <div class="overlay-color" ng-style="overlayColorStyles" ></div>
            <div class="overlay-text" ng-style="overlayTextStyles">VIEW</div>
        </div>
    </div>

<script>

    // Create the module
    var appModule = angular.module('appName', []);

    // Create rootScope variables
    appModule.run(
        function($rootScope){
            $rootScope.title = "Taneleer Demonstration";
        }
    );

    // Create the controller
    appModule.controller('appCtrl', function($scope, $http) {

        $scope.overlayColorStyles = {"opacity": 0};
        $scope.overlayTextStyles =  {"opacity": 0};

        $scope.makeVisibile = function(){
            //alert("test"); 
            //document.getElementById("overlay-color").style.opacity = .75;
            //document.getElementById("overlay-text").style.opacity = 1;
            $scope.overlayColorStyles = {"opacity" : .75};
            $scope.overlayTextStyles = {"opacity" : 1};

        }
        $scope.makeInVisibile = function(){
            //alert("test"); 
            //document.getElementById("overlay-color").style.opacity = 0;
            //document.getElementById("overlay-text").style.opacity = 0;
            $scope.overlayColorStyles = {"opacity" : 0};
            $scope.overlayTextStyles = {"opacity" : 0};

        }

        $http({
                method : "GET",
                url : "https://taneleer.composedcreative.com/api/v1/feed/a0329f16-9225-11e6-89bb-296a97b9d609/bb0429f6-f0ca-11e7-8f5d-d92739a9a53f"
            }).then(function mySucces(response) {

                $scope.myMessage = "Success!";

                $scope.response = response;
                $scope.meta = response.data.meta;
                $scope.outsideData = response.data;
                $scope.insideData = response.data.data;
                $scope.links = response.data.links;

                $scope.selfLink = response.data.links.self;
                $scope.firstLink = response.data.links.first;
                $scope.lastLink = response.data.links.last;
                $scope.nextLink = response.data.links.next;
                $scope.prevLink = response.data.links.prev;

                $scope.statuscode = response.status;
                $scope.statustext = response.statusText;
                $scope.statusheaders = response.headers(); 
                $scope.statusconfig = response.config;   

            }, function myError(response) {
                $scope.myMessage = "Error!";
                $scope.response = response;
                $scope.statuscode = response.status;
                $scope.statustext = response.statusText;
                $scope.statusheaders = response.headers(); 
                $scope.statusconfig = response.config;   
            });


        $scope.getNext = function() {
            $http({
                method : "GET",
                url : $scope.nextLink
            }).then(function mySucces(response) {

                $scope.myMessage = "Success!";
                $scope.response = response;
                $scope.outsideData = response.data;
                $scope.meta = response.data.meta;

                $scope.insideData = $scope.insideData.concat(response.data.data);

                $scope.links = response.data.links;
                $scope.selfLink = response.data.links.self;
                $scope.firstLink = response.data.links.first;
                $scope.lastLink = response.data.links.last;
                $scope.nextLink = response.data.links.next;
                $scope.prevLink = response.data.links.prev;

                $scope.statuscode = response.status;
                $scope.statustext = response.statusText;
                $scope.statusheaders = response.headers(); 
                $scope.statusconfig = response.config;   

            }, function myError(response) {
                $scope.myMessage = "Error!";
                $scope.response = response;
                $scope.statuscode = response.status;
                $scope.statustext = response.statusText;
                $scope.statusheaders = response.headers(); 
                $scope.statusconfig = response.config;   
            });
        }
        $(window).scroll(function() {
            if($(window).scrollTop() + $(window).height() == $(document).height()) {
                $scope.getNext();
            }
        });
    });

</script>

嗨,再次感謝您的回答亞倫。 我還有一個需要解決的問題。 我現在正在構建該應用的燈箱部分。 那就是您單擊查看按鈕時看到的覆蓋。 我已將最新版本在線放置在這里: http : //www.petermingione.com/my-demo/正如您所看到的,無論單擊哪個圖像,您單擊的唯一出現的圖像都是該集合中的第一幅圖像。 同樣,這是ng-repeat的另一個問題。 該圖像作為mainImage.url位於每個對象中,我正在ng-repeat循環中通過x.mainImage.url訪問它。 我不確定為什么它不起作用。 任何人都能給我的任何幫助將不勝感激。 該代碼在下面並在線提供:

   <style>
    * {
        box-sizing: border-box;
        font-family: sans-serif;
    }
    h1, 
    h2{
        margin-left:10px;
    }

    .outer-wrapper{
        overflow: hidden;
    }
    .inner-wrapper{
        display:inline-block;
        vertical-align:top;
        padding:5px;
        position:relative;
    }
    .inner-wrapper img{
        width:100%;
    }
    .inner-wrapper .outer-caption{
        color:black;
        width:100%;
        padding-top:35%;
        background-color:#fc7cab;
        position:relative;
    }
    .inner-wrapper .outer-caption .inner-caption{
        font-size:14px;
        font-family:sans-serif;
        overflow:hidden;
        width:75%;
        height:70px;
        position:absolute;
        top:0;
        left:0;
        bottom:0;
        right:0;
        margin:auto;
    }
    .inner-wrapper .item-overlay-color{
        position: absolute;
        top:0;
        bottom:0;
        left:0;
        right:0;
        margin:auto;
        background-color: #fff;
        transition: all .5s;
        opacity: 0.0;   
    }
    .inner-wrapper:hover .item-overlay-color {
        opacity: 0.75;
    }
    .inner-wrapper .item-overlay-text{
        border: 2px solid #7e7e7e;
        color:#7e7e7e;
        font-size: 10px;
        position: absolute;
        top:0;
        bottom:0;
        left:0;
        right:0;
        width:70px;
        height:35px;
        line-height:35px;
        margin:auto;
        border-radius:1px;
        text-align: center;
        transition: all .5s;
        opacity: 0.0;
    }
    .inner-wrapper:hover .item-overlay-text {
        opacity: 1.0;
    }
    .inner-wrapper .page-overlay {
        position: fixed;
        width: 100%;
        height: 100%;
        top: 0; 
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(255,255,255,0.75);
        z-index: 2;
        cursor: pointer;
    }
    .inner-wrapper #page-overlay {
        opacity:0;
        transition: all .5s;
        pointer-events:none;
    }
    .inner-wrapper .page-overlay .text{
        position: absolute;
        top: 50%;
        left: 50%;
        font-size: 50px;
        color: white;
        transform: translate(-50%,-50%);
        -ms-transform: translate(-50%,-50%);
    }
    .inner-wrapper .page-overlay .text .close{
        position:absolute;
        top:0;
        right:0;
        color:#000;
        font-weight: lighter;
        font-size: 30px;
        line-height: 30px;
        padding-top:5px;
        padding-right:5px;
    }

    @media screen and (min-width: 1301px){
        .inner-wrapper{
            width:16.6666%;
        }
    }
    @media screen and (max-width: 1300px){
        .inner-wrapper{
            width:20%;
        }
    }
    @media screen and (max-width: 1024px){
        .inner-wrapper{
            width:25%;
        }
    }
    @media screen and (max-width: 768px){
        .inner-wrapper{
            width:50%;
        }
    }
    @media screen and (max-width: 480px){
        .inner-wrapper{
            width:100%;
        }
    }

  </style>

 <body>
<div id="outer-wrapper" class="outer-wrapper">
    <div id="inner-wrapper" class="inner-wrapper" ng-repeat="x in insideData">
        <img ng-if="x.service=='Instagram'||(x.service=='Twitter' && x.mediaType=='image')" ng-src='{{x.thumbnails[0].url}}'>
        <div class="outer-caption" ng-if="x.service=='Twitter'&& x.mediaType!='image'">
            <div class="inner-caption">{{x.caption}}</div>
        </div>
        <div class="item-overlay-color"></div>
        <div class="item-overlay-text" ng-click="showOverlay()">VIEW</div>
        <div id="page-overlay" class="page-overlay">
                <div class="text">
                    <img ng-src='{{x.mainImage.url}}'>
                    <span class="close" ng-click="hideOverlay()">X</span>
                </div>
        </div>
    </div>
</div>
 </body>
  <script>
    // Create the module
    var appModule = angular.module('appName', []);

    // Create rootScope variables
    appModule.run(
        function($rootScope){
            $rootScope.title = "Taneleer Demonstration";
        }
    );

    // Create the controller
    appModule.controller('appCtrl', function($scope, $http) {

        $scope.showOverlay = function(){
            document.getElementById("page-overlay").style.opacity = 1;
            document.getElementById("page-overlay").style["pointer-events"] = "auto";
        }
        $scope.hideOverlay = function(){
            document.getElementById("page-overlay").style.opacity = 0;
            document.getElementById("page-overlay").style["pointer-events"] = "none";
        }

        $http({
                method : "GET",
                url : "https://taneleer.composedcreative.com/api/v1/feed/a0329f16-9225-11e6-89bb-296a97b9d609/bb0429f6-f0ca-11e7-8f5d-d92739a9a53f"
            }).then(function mySucces(response) {

                $scope.myMessage = "Success!";

                $scope.response = response;
                $scope.meta = response.data.meta;
                $scope.outsideData = response.data;
                $scope.insideData = response.data.data;
                $scope.links = response.data.links;

                $scope.selfLink = response.data.links.self;
                $scope.firstLink = response.data.links.first;
                $scope.lastLink = response.data.links.last;
                $scope.nextLink = response.data.links.next;
                $scope.prevLink = response.data.links.prev;

                $scope.statuscode = response.status;
                $scope.statustext = response.statusText;
                $scope.statusheaders = response.headers(); 
                $scope.statusconfig = response.config;   

            }, function myError(response) {
                $scope.myMessage = "Error!";
                $scope.response = response;
                $scope.statuscode = response.status;
                $scope.statustext = response.statusText;
                $scope.statusheaders = response.headers(); 
                $scope.statusconfig = response.config;   
            });


        $scope.getNext = function() {
            $http({
                method : "GET",
                url : $scope.nextLink
            }).then(function mySucces(response) {

                $scope.myMessage = "Success!";
                $scope.response = response;
                $scope.outsideData = response.data;
                $scope.meta = response.data.meta;

                $scope.insideData = $scope.insideData.concat(response.data.data);

                $scope.links = response.data.links;
                $scope.selfLink = response.data.links.self;
                $scope.firstLink = response.data.links.first;
                $scope.lastLink = response.data.links.last;
                $scope.nextLink = response.data.links.next;
                $scope.prevLink = response.data.links.prev;

                $scope.statuscode = response.status;
                $scope.statustext = response.statusText;
                $scope.statusheaders = response.headers(); 
                $scope.statusconfig = response.config;   

            }, function myError(response) {
                $scope.myMessage = "Error!";
                $scope.response = response;
                $scope.statuscode = response.status;
                $scope.statustext = response.statusText;
                $scope.statusheaders = response.headers(); 
                $scope.statusconfig = response.config;   
            });
        }
        $(window).scroll(function() {
            if($(window).scrollTop() + $(window).height() == $(document).height()) {
                $scope.getNext();
            }
        });
    });

我知道您問過如何以角度的方式進行此操作,但是ng-mouseenter和ng-mouseleave的性能非常高,如果您打算在現實世界中的應用中使用它,則應該使用CSS來完成。

我將繼續向您展示如何修復您的版本,然后為您提供更高效的CSS版本:)

對於此用例,有一個非常有用的變量$ index,可以在ng-repeat標簽內部任何地方的角度模板中引用該變量,以獲取要迭代的當前數據項的索引。 您應該使用它來保存當前懸停在控制器范圍內的項目的索引。 然后,當鼠標離開項目時,您可以放棄保存的索引。

然后,當您分配樣式時,您可以使用三元數來根據項目索引與保存在范圍內的活動索引變量相匹配來分配活動或非活動樣式。

另外,如果您不熟悉,三元表達式是條件語句的簡寫形式,形式為conditional_expression ? value_returned_if_true : value_returned_if_false conditional_expression ? value_returned_if_true : value_returned_if_false 這非常適合在javascript中編寫非常簡潔的條件語句(或在這種情況下,帶有解釋javascript的角度模板:))

因此,在此示例中,我結合使用了三元表達式並保存了鼠標輸入的最后一項的索引,以將鼠標懸停或未懸停的樣式分配給每個項目。

和示例的縮寫版本:

角度控制器:

app.controller('exampleController', function($scope) {
  $scope.overlayColorStyles = {"opacity": 0};
  $scope.overlayTextStyles  = {"opacity": 0};
  $scope.overlayTextStylesActive  = {"opacity": 1};
  $scope.overlayColorStylesActive = { "opacity": .75};
  $scope.activeItemIndex    = null;
});

模板:

<div id="outer" class="outer">
  <div class="inner"
      ng-mouseenter="$scope.activeItemIndex = $index"
      ng-mouseleave="$scope.activeItemIndex = null"
      ng-repeat="x in insideData">
      <img ng-if="x.service=='Instagram'||(x.service=='Twitter' && x.mediaType=='image')" ng-src='{{x.thumbnails[0].url}}'>
      <div ng-if="x.service=='Twitter'&& x.mediaType!='image'" class="outer-caption"><div class="inner-caption">{{x.caption}}</div></div>
      <div class="overlay-color"
        ng-style="$scope.activeItemIndex === $index ? overlayColorStylesActive : overlayColorStyles">
      </div>
      <div class="overlay-text"
        ng-style="$scope.activeItemIndex === $index ? overlayTextStylesActive : overlayTextStyles">
        VIEW
      </div>
  </div>
</div>

同樣,此代碼僅應用於學習練習。 Angular的工作不是應用基於用戶交互的樣式,如果您嘗試以這種方式使用樣式,則當您開始添加更多項時,應用程序將變得非常慢。 用css做到這一點非常簡單,並且可以顯着提高性能:)

下面的css版本:

HTML:

<div id="outer" class="outer">
  <div class="inner"
      ng-repeat="x in insideData">
      <img ng-if="x.service=='Instagram'||(x.service=='Twitter' && x.mediaType=='image')" ng-src='{{x.thumbnails[0].url}}'>
      <div ng-if="x.service=='Twitter'&& x.mediaType!='image'" class="outer-caption"><div class="inner-caption">{{x.caption}}</div></div>
      <div class="overlay-color"></div>
      <div class="overlay-text">VIEW</div>
  </div>
</div>

CSS

.overlay-color {
  opacity: 0.0;
}

.overlay-text {
  opacity: 0.0;
}

.inner:hover .overlay-text {
  opacity: 1.0;
}

.inner:hover .overlay-color {
  opacity: 0.75;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM