11

我试图弄清楚如何将工具提示的内容与角度绑定。我有一个看起来像这样的指令:

脚本.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 插件

我的 index.html 看起来像这样(请注意,在实际文件中,我已将所有源代码都包含在 head 中,我只是没有将其粘贴到此处以避免混乱):

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

按钮.html

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

正如您在指令代码中看到的那样。button.html 被加载到工具提示中,但是这会阻止 angular 正常工作——当 button.html 加载到弹出窗口时,ng-click 不起作用。那是因为 Angular 不知道它。

我也知道 button.html 是有效的,因为只需添加

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

到 index.html 工作正常(即点击按钮执行 someFunction())

所以我的问题是:

如何将工具提示的实际内容与角度绑定?如果不是内容,有没有办法绑定工具提示,让 Angular 知道它?我熟悉 $scope.$apply() 但我不太确定如何在这里使用它。

4

1 回答 1

15

更新 1 从 HTML 转换为 javascript 时,请确保从蛇形转换为驼峰转换。所以init-toolbar在 html 中转换为initToolbar在 javascript 中。

这是一个工作示例:http ://plnkr.co/edit/l2AJmU?p=preview

HTML

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

按钮.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
              }
            });

          });

        }
    }
});

原来的

按钮不起作用的原因是 angular 不知道它应该绑定到它。你告诉 Angular 使用$compile来做到这一点。我对那个qTip2插件了解不多,但是如果你加载模板,然后编译它 $compile(template)(scope);然后交给qTip2,你会得到你期望的结果。

于 2013-07-30T13:38:33.757 回答