bmw0128
bmw0128

Reputation: 13698

Angular scope issue in a Controller and a Directive

I have the following in a controller:

 Restangular.all('foos').getList().then(
    function(foos) {
        $scope.foos = foos;
    });

In an HTML page, I am able to do the following:

<div ng-repeat="foo in foos | orderBy:'fooName'">

I want to move the ng-repeat to a directive, so I have the following in a directive:

app.directive('interactionFoos', function(){

return {
    restrict: 'A',
    scope : false,
    link: function($scope, $element, $attrs) {

        //console.log("*** size: " + $scope.foos.length);
    }
}

});

And in the HTML I will have:

<div interaction-foos></div>

In the directive, I am getting undefined for $scope.foos. As a test, in the controller, I hard coded: $scope.test= 'foobar'. Then, in the directive, I replaced the log line with the following and it printed 'foobar':

console.log("*** test: " + $scope.test);

I do not know why $scope.test is working as I expect, but $scope.foos is not?

Upvotes: 1

Views: 53

Answers (2)

Shawn C.
Shawn C.

Reputation: 6841

I believe this is an Async issue as Restangular would run as a promise so foo would not be set when the directive link function runs. To get around this you need to add a watch to see when the scope has changed

$scope.$watch('foos', function(newValue, oldValue) { console.log(newValue, oldValue); });

Upvotes: 1

user273895
user273895

Reputation: 654

do something like this:

angular.module("app", [])
.controller("interactionCtrl", function($scope) {
  $scope.foos = ["A", "B", "C"];
 })
.directive("interactionFoos", function() {
  return {
    restrict: 'A',
    scope: {
      foos: '='
    },
    link: function(scope, element, attrs) {
      alert(scope.foos.length);
    }
  };
});
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<div ng-app="app" ng-controller="interactionCtrl">
    <div interaction-foos foos="foos"></div>
</div>

basically the foos in the directive binds to the foos that are exposed on the controller.

also in your linking function don't use $ in the name of the function arguments, for example call the first argument scope instead of scope, because those arguments are not really injected to the link function (it's a regular function call, if you name the first argument bob it will still be equal to the scope)

Upvotes: 0

Related Questions