简体   繁体   中英

Call JQuery plugin through Link function of Directive Angularjs

I dont know what exactly happend to this belove code

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

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

If i remove setTimeout in link function, code not working. Can explain to me what AngularJs work with this code. 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/

TL;DR;

Angular won't "know" what happened inside setTimeout , if you use $setTimeout , that callback will be called inside Angular's digest cycle.

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. Usually you'll find this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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