User directive link function called before ng-repeat

I have the following directive:

.directive("picSwitcher", ["$timeout", function($timeout){
return {
    restrict: "A",
    scope: {
        pics: "=",
        fadeTime: "@",
        timeForPic:"@"
    },
    template: '<img ng-repeat="pic in pics" src="{{pic.url}}" style="display: none"/>',
    link:   function ($scope, element){
                //some code...
                $(element.find("img")[0]).css({display: "block"});
            }
};
}])

My problem is when my link function is called - ng repeat is not yet “compiled” (which word should be used here instead of compiling?)

so i am trying to set css undefined .. how can i get the link function to work after ng-repeat completes ?!

while I solve it, replacing $(element.find("img")[0]).css({display: "block"});with$timeout(function(){ $(element.find("img")[0]).css({display: "block"});}, 200);

but he feels "hacked"

Is there something that I am missing to achieve my goal in a simpler way? in general, what is the best way to manipulate the ng-repeat dom element inside the link function of a user directive?

Thanks, Jimmy.

+4
2

$scope.$evalAsync

$scope.$evalAsync(function(){
    $(element.find("img")[0]).css({display: "block"});
}

dom.

, $timeout , 0

$timeout(function(){
    $(element.find("img")[0]).css({display: "block"});}, 
0);

, .

http://www.bennadel.com/blog/2605-scope-evalasync-vs-timeout-in-angularjs.htm

+1

JQLite .ready().

    post: function postLink(scope, element) {
      element.ready(function() {
        //$(element.find("li")[0]).css({color: "red"});
        element.find("li:first-child").css({color: "red"});
      });
    }

. element, JQLite. , css, CSS.

<img> <ul><li>, .

function myDirective() {
  return {
    template : '<ul><li ng-repeat="pic in pics">{{pic.name}}</li></ul>',
    scope: {
      pics: '='
    },
    link: function(scope, element) {
        element.ready(function() {
          //$(element.find("li")[0]).css({color: "red"});
          element.find("li:first-child").css({color: "red"});
        });
    }
  }
}
function SuperController() {
	this.pics = [{name:"rob"}, {name:"jules"}, {name:"blair"}];
}
angular.module('myApp', []);
angular
    .module('myApp')
    .controller('SuperController', SuperController)
    .directive('myDirective', myDirective);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="SuperController as s">
    <my-directive pics="s.pics">
    </my-directive>
  </div>
</div>
Hide result
0

All Articles