在AngularJS 1.6中悬停时,在md-select / md-options上显示图像/背景

时间:2017-05-20 12:18:02

标签: javascript angularjs angularjs-directive angularjs-scope

我试图将鼠标悬停在AngularJS素材md-select下拉列表中,其中在悬停时,它会在div / span旁边显示旁边的图片。我将下面的代码统一起来,但它还没有来:

<md-select id="{{mapping.id}}" ng-model="mapping.value">
  <md-option ng-value="option" 
             ng-mouseenter="show = true" 
             ng-mouseleave="show = false" 
             ng-repeat="map in mapping.values" 
             ng-selected="$first">{{maping.options[$index]}}</md-option>
  <span ng-show="show">
      <img src="{{mapping.image[$index]}}" 
           align-"right" width="60px" 
           height="40px" 
           vertical-align="top"/>
  </span>
</md-select>

并在app中使用以下内容:

scope.shopw = false;

我们可以看一下悬停吗?如下所示,http://plnkr.co/edit/j5LBYQCXvN9LhXt25tTb?p=preview

1 个答案:

答案 0 :(得分:1)

你可以通过像我为你所做的那样写一个自己的directive来实现这一点。请检查 runnable fiddle demo

查看:

<div ng-app="sandbox" ng-controller="myCtrl">
  <div layout-gt-sm="row" layout="column" layout-margin>
    <main flex-md="60" flex-order-gt-sm="2">
      <h1 class="md-title">
        Main Content
      </h1>
      <div layout="row" layout-xs="column">
        <div flex="60">
          <md-select ng-model="mapping.value">
            <md-option ng-value="map.name"
                       ng-repeat="map in mapping.values" 
                       ng-selected="$first"
                       container-image
                       class="image-container"
                       image="map.image">{{map.name}}</md-option>
          </md-select>
        </div>
      </div>
    </main>
  </div>
</div>

CSS

._md {
  overflow: visible;
}

.preview-image {
  position: absolute;
  height:100px;
  width:100px;
  right: -140px;
}

应用:

var myApp = angular.module('sandbox', ['ngMaterial']);

myApp.controller('myCtrl', function($scope) {
  $scope.mapping = {
    value: null,
    values: [ {
        name: "1",
        image: "http://placehold.it/100x100"
      }, {
        name: "2",
        image: "http://placehold.it/100x100"
      }, {
        name: "3",
        image: "http://placehold.it/100x100"
      },
    ]
  }
});

myApp.directive('containerImage', function($compile) {
  return {
    restrict: 'A',
    scope: {
      image: "="
    },
    link: function (scope, element, attrs) {

      element.on('mouseover', function (e) {
        if (element.find("img").length === 0) {
          var imageElement = angular.element('<img class="preview-image" src="'+ scope.image +'" height="100" width="100" />');
          element.append(imageElement);
          $compile(imageElement)(scope);
        } else {
          element.find("img").attr('style', 'display:block');
        }
      });

      element.on('click', function (e) {
          element.find("img").attr('style', 'display:none');
      });

      element.on('mouseleave', function (e) {
          element.find("img").attr('style', 'display:none');
      });
    }
  }
});