0

My directive has a controller and I am trying to figure out how to pass a value from the directive that was passed in. In the example below 'name' is not valid posted to the console but it shows in the html when rendered. Obviously my example is an over simplication, but you get the point.

angular.module('myApp')
    .directive('helpLabel', function() {
        return {
            restrict: 'E',
            scope: {
                name: '@',
            },
            template: '<span>{{name}}</span>',
            controller: function ($scope) {                
                console.log(name);
            } 
        };
    });
<helpLabel name="test"></helpLabel>
silvster27
  • 1,916
  • 6
  • 30
  • 44

3 Answers3

1

The answer I found is to use bindToController along with controllerAs now effective angular 1.4.

angular.module('myApp')
.directive('helpLabel', function() {
    return {
        restrict: 'E',
        scope:{},
        bindToConroller: {
            name: '@',
        },
        template: '<span>{{cntrl.name}}</span>',
        controller: function () {                
            console.log(cntrl.name);
        },
        controllerAs: "cntrl"
    };
});

http://blog.thoughtram.io/angularjs/2015/01/02/exploring-angular-1.3-bindToController.html

silvster27
  • 1,916
  • 6
  • 30
  • 44
0

This is because when it is being rendered to the html, you encapsulated name within {{}}. If you wan't to access the name property within your directive you have to change your code.

angular.module('myApp')
.directive('helpLabel', function() {
    return {
        restrict: 'E',
        scope: {
            name: '@',
        },
        template: '<span>{{name}}</span>',
        controller: function ($scope) {                
            console.log($scope.name);
        } 
    };
});
Oscar Vazquez
  • 437
  • 4
  • 8
0

In your code, console.log(name);, the variable name is not known your directive and hence not able to access it, but since angular has done binding to 'name' variable, it can render {{name}}.

You should access variable name as $scope.name as variable name is present inside current scope.

Modify your code as follow:

angular.module('myApp')
    .directive('helpLabel', function() {
        return {
            restrict: 'E',
            scope: {
                name: '@',
            },
            template: '<span>{{name}}</span>',
            controller: function ($scope) {                
                console.log($scope.name);
            } 
        };
    });
Rajeev Jayaswal
  • 1,423
  • 1
  • 20
  • 22