Search code examples
angularjsdata-bindingangularjs-directiveangularjs-scopeangular-controller

Passing Controller's $scope variable to nested directive's controller


I'm having trouble passing a scope object from one controller to a nested directive's controller. I have a directive (child) within another directive (parent), the parent directive and its controller look like this:

myApp.directive('parent', function(){
    return {
        restrict : 'E',
        scope:false,
        controller: 'parentController',
        templateUrl : '/templates/parent.html',
    };
});

myApp.controller('parentController', ['$scope',
function Controller($scope) {
    $scope.monitors=[monitor1,monitor2,monitor3]; //in reality these are JSON objects
}

My 'parent.html' template looks like this:

<div>
    <!-- Other things go here -->
    <div ng-repeat='monitor in monitors'>
        <child monitorData='monitor'></child>
    </div>
</div>

The child directive and its controller look like this:

myApp.directive('child', function(){
    return {
        restrict : 'E',
        scope:{
            monitorData:'=',
        },
        bindToController:true,
        controller: 'childController',
        templateUrl : '/templates/child.html',
    };
});

myApp.controller('childController', ['$scope', function ChildController($scope) {
    var vm=this;

    console.log('instantiated childController');
    console.log(vm);
}]);

The console output is this:

instantiated childController
ChildController
    monitorData : undefined

Any ideas?


Solution

  • Use monitor-Data insted of monitorData.

    <div>
    <!-- Other things go here -->
    <div ng-repeat='monitor in monitors'>
        <child monitor-Data='monitor'></child>
    </div>
    

    From angular documentacion: Note: These =attr attributes in the scope option of directives are normalized just like directive names. To bind to the attribute in < div bind-to-this="thing">, you'd specify a binding of =bindToThis.

    https://docs.angularjs.org/guide/directive