2014-01-25 58 views
6

我試圖在角度應用程序中使用ElevateZoom jQuery插件。ElevateZoom jQuery插件的AngularJS指令

從本質上講,使用ElevateZoom通常情況下,你創建一個圖片如下:

<img id="my-img" src="small.jpg" data-zoom-image="big.jpg" /> 
在應用程序中JS

然後:

$('#my-img').elevateZoom(options); 

這工作正常,在標準的應用程序。但是當我嘗試在我的AngularJS應用程序中使用指令(我遵循一些SO解決方案將jQuery插件變爲帶指令的角度)時,我無法使其工作。在Plunkr

現場演示編輯:http://plnkr.co/edit/Mu4EOcGtGs7XVDDUvnnB?p=preview

我的指令看起來像:

app.directive('ngElevateZoom', function() { 
    return { 
    restrict: 'A', 
    scope: true, 
    compile: function(scope, element, attrs) { 
     $(element).elevateZoom(scope.$eval(attrs.elevateZoom)); 
    } 
    }; 
}); 

我的HTML看起來像這樣:

<img ng-elevate-zoom ng-src="{{small_image}}" data-zoom-image="{{large_image}}" /> 

我在做什麼錯?我只是一直在嘗試用角幾天這樣下去容易在我身上;)

回答

15

你的指令:

app.directive('ngElevateZoom', function() { 
    return { 
    restrict: 'A', 
    scope: true, 
    compile: function(scope, element, attrs) { 
     $(element).elevateZoom(scope.$eval(attrs.elevateZoom)); 
    } 
    }; 
}); 

記住compile功能(tElement,tAttrs,transclude){...}沒有訪問範圍,所以我想你試圖使用link函數。

檢查here

我做了一些變化:

HTML

<img ng-elevate-zoom 
    ng-src="{{small_image}}" 
    zoom-image="{{large_image}}" /> 

JS

app.directive('ngElevateZoom', function() { 
    return { 
    restrict: 'A', 
    link: function(scope, element, attrs) { 
     element.attr('data-zoom-image',attrs.zoomImage); 
     $(element).elevateZoom(); 
    } 
    }; 
}); 

當使用直銷TLY data-zoom-image='{{large_image}}',是造成該elevateZoom試圖讓從該屬性的值,並在運行該插件的時間爲「{{large_image}}」 $(element).elevateZoom();

enter image description here

檢查更新Plunker


修訂

由於可能有情況下,當ATTRS需要插件的延遲ed,你需要$observe attr,並且只有當它真的準備好時纔會調用插件。

app.directive('ngElevateZoom', function() { 
    return { 
    restrict: 'A', 
    link: function(scope, element, attrs) { 

     // Watch for changes on the attribute before 
     // calling the function. 
     attrs.$observe('zoomImage', function() { 
     linkElevateZoom(); 
     }); 

     function linkElevateZoom() { 
     // Check that it's not empty. 
     if (!attrs.zoomImage) return; 
     element.attr('data-zoom-image',attrs.zoomImage); 
     $(element).elevateZoom(); 
     } 

     linkElevateZoom(); 
    } 
    }; 
}); 

檢查更新plunker

可選 當與意見結合使用此,該插件葉視圖頂部的DIV分層後面。這是一個解決這個問題的指令。

app.directive('zoomContainer', function() { 
    return { 
     restrict: 'A', 
     link: function(scope, element, attrs) { 
      scope.$on('$routeChangeSuccess', function() { 
       var target = element.children('div.zoomContainer').remove(); 
      }); 
     } 
    }; 
}); 

該指令需要應用於body元素。

<body zoom-container> 
+0

這很完美。謝謝! –

+0

好吧,其實它似乎與上述輕微問題。當我在$ scope.data = {large:...,small:...}中存儲網址並在數據加載完成後分配它們時,該指令似乎無法工作:(我嘲笑它在http://plnkr.co/edit/3koXtpAtouVXmnA3HZDW?p=preview上,如果你能看到你的解決方案是否可以改變來處理這個問題,那將是了不起的?我測試過了,看起來這個指令是用數據初始化的對象未定義,所以需要重新初始化或什麼? –

+0

我覺得從SO和Angular docs看,我可能需要做一些解決方案/承諾,但我不知道如何適用以及如何正確實施它它很適合我的指示 –