0

Still new in Angular world and I have a categoriesController wrapping a custom directive categories-select like this:

<div ng-controller="categoriesController" ng-init="init()">
    <categories-select></categories-select>
</div>


angular.module('app')
    .directive('categoriesSelect', [function () {
    return {
        restrict: "E",
        templateUrl: 'categoriesSelectTemplate',
        controller: ['$scope', function ($scope) {

            console.log($scope)
            console.log($scope.categories)
        }],
    }
}])

The categoriesController has an array of categories.

The strange behavior I get inside the directive is:

enter image description here

So, whenever I try to get the categories array to do something with it, I find that it's empty, but it's -at the same time- populated in the $scope!

I tried also to isolate the directive scope and pass the array object to it, but I got the same strange behavior, but anyway, I want to know why this simple code doesn't work.

1 Answer 1

1

I always pass necessary parameters inside directive, never share parent scope. So looking on each directive you see what is required, never got unknown behaviour.

so Angular directive:

angular.module('app')
.directive('categoriesSelect', [function () {
return {
    restrict: "E",
    scope: {
       categories: '='
    },
    templateUrl: 'categoriesSelectTemplate',
    controller: ['$scope', function ($scope) {

        console.log($scope)
        console.log($scope.categories)
    }],
}
}])

and HTML:

<categories-select categories="categories"></categories-select>

Edited:

I think your directive controller is getting initialised before categories coming from parent scope. try to draw categories on directive HTML and you will get them, or use $scope.$watchCollection inside directive controller

$scope.$watchCollection('categories', function (newVal, oldVal) {      
     console.log(newVal); 
}); 
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, you saved me! your "Edit" was right, but still don't understand why the first console.log shows the array as populated?
this is browser console magic! by the time browser prints $scope, categories already there, but printing direct field like $scope.categories browser understand it is still empty... don't know. looks like consoling $scope is bad approach is you got some missunderstanding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.