Help me to understand.

There is a controller. Data comes to it, all is well.

function interviewCtrl($scope, InterviewFactory){ $scope.interview = []; InterviewFactory.getInterview().success(function(data){ $scope.interview = data; }); } 

I create a directive:

 app.directive('ngDatelimit', function () { return { restrict: 'E', link: function(scope){ console.log(scope); } }; }); 

In the console I see the contents of the osprey, including the interview object. But I can not access the scope.interview , returns an empty object.

How to get the contents of the already filled $scope.interview ?

  • how do you want to use it later? - Grundy
  • @Grundy, at least just process and return via template - Pavel Sokolov
  • if you just show it in a template, you don’t need to do anything, immediately in the template and use it. the angular itself will substitute what is needed when the data appears - Grundy
  • @Grundy, this is logical. But what if I need to work with this data in a directive? - Pavel Sokolov
  • in this case, only $watch - or make a service call directly inside the directive. - Grundy

1 answer 1

Since the value of the field is assigned asynchronously, then at the time of the execution of the link method, the value in most cases will not be filled yet.

As a solution, you can consider several approaches:

  1. $watch - add an observer, and when the value changes - do the necessary actions

     link: function(scope){ var unwatch = scope.$watch("interview",function(newValue, oldValue){ if(newValue != []){ // если значение не пустой массив // значит запрос что-то вернул. можно что-то делать unwatc();//так как получаем только один раз, нет нужды наблюдать за изменениями дальше, убираем наблюдателя } }); } 
  2. Call the service directly inside the directive, for example, adding it to the controller directive

     controller: function($scope, InterviewFactory){ InterviewFactory.getInterview().success(function(data){ $scope.interview = data; }); } 
  3. save the request

     $scope.getInterview = InterviewFactory.getInterview(); 

    then in the link method add the function success to it

     link: function(scope){ scope.getInterview.success(function(data){ $scope.interview = data; }); } 
  4. use the filter directly in the view

  • Made in $ watch. Thanks for the answer! - Pavel Sokolov