【问题标题】:Call JQuery plugin through Link function of Directive Angularjs通过Directive Angularjs的Link函数调用JQuery插件
【发布时间】:2016-06-20 12:39:29
【问题描述】:

我不知道这个爱的代码到底发生了什么

模板:

<article class="thumb" ng-repeat="product in store.products">
    <a href="{{product.largeImg}}" class="image" ><img ng-src=" {{product.smallImg}}" alt="" /></a>
    <h2>{{product.index}}. {{product.title}}</h2>
    <p>{{product.desc}}</p>
</article>

指令

 mainApp.directive('contentdir', function () {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: 'template.html',
        controller: ['$scope', '$http', function ($scope, $http) {
                $scope.store = {};
                $http.get('/getTemplate').success(function (data) {
                    $scope.store.products = data;
                });
            }],
        link: function ($scope, $element, attr) {
        setTimeout(function () {$('#main').poptrox({
                    baseZIndex: 20000,
                    /*options of poptrox*/
                });
            }, 10);
        }
    };
});

html

    <div id="main">
            <contentDir></contentDir>
    </div>

如果我在链接函数中删除 setTimeout,代码将无法正常工作。可以向我解释 AngularJs 使用此代码的工作原理。非常感谢。

【问题讨论】:

  • setTimeout 中的代码没有使用 $element 或与指令没有任何关系。为什么它在链接函数中?
  • 使用 jquery 插件的模板效果,我尝试在 Angularjs 中使用它。
  • 我认为 Muthukannan 所问的是为什么你的指令作用于它之外的元素,这并不反映指令的用途。你不应该删除#main div 并且也许这样做:$element.poptrox() 在指令中?

标签: javascript jquery angularjs angularjs-directive


【解决方案1】:

您应该使用$timeout 提供程序而不是setTimeout,请参阅:http://www.codelord.net/2015/10/14/angular-nitpicking-differences-between-timeout-and-settimeout/

TL;DR;

Angular 不会“知道”setTimeout 内部发生的事情,如果您使用 $setTimeout,则该回调将在 Angular 的摘要循环中调用。

编辑:我错过了你的问题。

无论哪种方式你都应该使用$timeout,你需要$timeout的原因是因为你需要Angular来创建一个单独的摘要循环,如果你让代码同步运行,它不会像Angular那样工作请注意这种变化。通常你会发现:

$timeout(function(){
  // do something I want angular to be aware of. i.e.: a jQuery plugin
}, 0);

【讨论】:

  • 他说如果他删除 setTimeout,代码就不能工作,否则就不行。
  • Tks 回复,当我 setDelay = 0 超时,代码仍然不工作,但将延迟更改为 20 或 50 毫秒,它工作。可能是我猜问题涉及在浏览器或其他东西中渲染。
猜你喜欢
  • 1970-01-01
  • 2017-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 2016-11-24
  • 2016-04-19
  • 1970-01-01
相关资源
最近更新 更多