2013-07-29 61 views
11

我想弄清楚如何綁定帶有角度的工具提示的內容。我有一個指令,看起來像這樣:AngularJS綁定jQuery qTip2插件

的script.js

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

myApp.directive('initToolbar', function(){ 
    return { 
     restrict: 'A', 
     link: function(scope, element, attrs) 
     { 
      $(element).qtip({ 
       content: { 
        ajax: 
        { 
         url: 'button.html' 
        } 
       }, 
       position: { 
        my: 'bottom left', 
        at: 'bottom middle', 
        target: $(element) 
       }, 
       hide: { 
        fixed : true, 
        delay : 1000 
       } 
      }); 
     } 
    } 
}); 

它使用qTip2插件from here

我的index.html像這樣(請注意,在實際的文件我有包括在頭部的所有來源,我只是不在這裏粘貼以避免混亂):

<body> 
    <div initToolbar> 
     <p> 
      Hover over me. Hover over me. Hover over me. 
     </p> 
    </div> 
</body> 

button.html

<div ng-controller="myController"> 
    <button ng-click="someFunction()">Click me</button> 
</div> 

正如你可以在指令代碼中看到。 button.html被加載到工具提示中,但是這可以防止角度正常工作 - 當button.html加載到彈出窗口時,ng-click不起作用。那是因爲角度不知道它。

我也知道,button.html是有效的,因爲簡單地添加

<ng-include src="'button.html'"> 

到index.html的正常工作(即點擊按鈕,執行someFunction())

所以我的問題是:

如何將角度的工具提示的實際內容綁定?如果不是內容,有沒有辦法綁定工具提示,所以角度知道它? 我很熟悉$ scope。$ apply(),但我不太清楚如何在這裏使用它。

+0

嘿我更新了我的答案與工作plunkr。希望它仍然可以幫助你。普朗克不在我的辦公室工作:-( –

回答

15

UPDATE 1 請確保從角度從HTML轉換爲javascript時,從蛇形案例轉到camelCase。因此,html中的init-toolbar轉換爲javascript中的initToolbar

這裏是一個工作示例:http://plnkr.co/edit/l2AJmU?p=preview

HTML

<div init-toolbar=""> 
    <p> 
    Hover over me. Hover over me. Hover over me. 
    </p> 
</div> 

Button.html

<div> 
    <button ng-click="someFunction()">Click me</button> 
</div> 

JAVACRIPT

var app = angular.module('plunker', []); 

app.controller('MainCtrl', function($scope) { 
    $scope.name = 'World'; 
    $scope.someFunction = function() { 
    $scope.name = 'FOO BAR'; 
    }; 
}); 

app.directive('initToolbar', function($http, $compile, $templateCache){ 
    return { 
     restrict: 'A', 
     link: function(scope, element, attrs) 
     { 
      $http.get('button.html', {cache: $templateCache}). 
      success(function(content) { 
       var compiledContent = $compile(content)(scope); 

       $(element).qtip({ 
       content: compiledContent, 
       position: { 
        my: 'bottom left', 
        at: 'bottom middle', 
        target: $(element) 
       }, 
       hide: { 
        fixed : true, 
        delay : 1000 
       } 
      }); 

      }); 

     } 
    } 
}); 

ORIGINAL

按鈕不起作用的原因是因爲角度不知道它應該綁定到它。你告訴角色使用$compile來做到這一點。我對qTip2插件瞭解不多,但如果你加載模板,然後編譯它$compile(template)(scope);然後把它交給qTip2,你會得到你期望的結果。

+0

如果可能,你可能會給一個小的代碼片段。我瀏覽了角度文檔,他們總是在指令中定義的模板上調用$ compile。在這種情況下,我指的是一個jqueryObject(qTip),它不一定是一個模板,內部內容也指向一個url(button.html)。對不起,我不清楚$編譯和如何使用它。 – Naveed

+1

是的,我正在嘗試製作一個plunkr,但由於某種原因它失敗了。我會稍後檢查並嘗試發佈一些內容。 –

+0

從我瞭解qTip應用到使用jQuery的元素後,運行時qtip對象的更改將不會應用。例如,如果我們更改爲:bottom middle => at:右上角(通過向該指令傳遞參數)將不會產生效果。 – masimplo