简体   繁体   English

通过指令Angularjs的Link函数调用JQuery插件

[英]Call JQuery plugin through Link function of Directive Angularjs

I dont know what exactly happend to this belove code 我不知道这个belove代码到底发生了什么

Template: 模板:

<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>

Directive 指示

 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 html

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

If i remove setTimeout in link function, code not working. 如果我删除链接功能中的setTimeout,代码将无法正常工作。 Can explain to me what AngularJs work with this code. 可以向我解释一下AngularJs可以使用此代码。 Thank you so much. 非常感谢。

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

TL;DR; TL; DR;

Angular won't "know" what happened inside setTimeout , if you use $setTimeout , that callback will be called inside Angular's digest cycle. Angular不会“知道” setTimeout内部发生了什么,如果使用$setTimeout ,则该回调将在Angular的摘要周期内调用。

EDIT: I missread your question. 编辑:我错过了你的问题。

Either way you should use $timeout , the reason you need $timeout is because you need angular to create a separate digest cycle, if you leave the code to run synchronously, it won't work as Angular won't be aware of that change. 无论哪种方式,您都应该使用$timeout ,之所以需要$timeout是因为您需要用angular来创建一个单独的摘要周期,如果您让代码同步运行,它将无法正常工作,因为Angular不会意识到这一变化。 Usually you'll find this: 通常您会发现:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM