Search code examples
angularjsangular-directive

Accessing data out of parent controller with Controller as


I am working through the book Learning Angular Js by Brad Dayley. The book uses $scope in its examples. I am pushing myself to use controllerAs. In chapter seven the book focuses on creating custom directives.

I created a simple one similar to the example provided. Inside I am setting transclude to true. I am using the link function to append a footer to the parent div. Inside of the footer tag the author of the book calls scope.$parent.title In the example the title value comes from the parent controller.

  .directive('myBox', function() {
        return {
            transclude: true,
            restrict: 'E',
            scope: {title: '@', bwidth: '@bwidth'},
            template: "<div><span class='titleBar'>{{title}}"+ "</span> <div ng-transclude></div></div>",
            link:function(scope, elem, attr, controller, transclude) {
                console.log('scope', scope.$parent)
                console.log('controller', controller);
                elem.append('<span class="footer">'+ scope.$parent.title + '</span>');
                elem.css('border', '2px ridge black');
                elem.css('display', 'block');
                elem.css('width', scope.bwidth);
            }
        }
    })

Inside of the book the controller uses $scope, I wanted to use controller as and am using vm to equal this. Here is my function for the controller. The vm.title is supposed to be the value on the footer.

I am getting undefined from my console when I check the value.

function FunCtrl() {
    var vm = this;

    vm.title = "myApplication";
}

Here is a plunker of what I am trying

http://plnkr.co/edit/uUeKrTwLOfkcGpkTU1Uz?p=preview


Solution

    • When you use ng-controller syntax, it's just calling the members of the controller like "start()" in the scope.

       <input ng-click="start()" type="button" value="Button"/>
    

    • But when you use controllerAs syntax, an instance of the controller is created and assigned to the reference variable that you have provided - "fun". So whatever you have defined in the controller is accessible only by using the reference. - "fun.start()" in the scope.

       <input ng-click="fun.start()" type="button" value="Button"/>
    

    Therefore you have to do the same when accessing the parent scope members if you have used controllerAs syntax like shown below

    scope.$parent.fun.title
    

    Demo

    Note The controller you are outputting in console is the one that belongs to the directive which you have not defined.