Travis Libby
Travis Libby

Reputation: 71

How should I use controller as syntax with angular directives?

Let's say for example I have this controller:

    function MainController() {

         var self = this;

         self.employee = {
             name: 'Travis Libby',
             occupation: 'Frontend Engineer'
         };

    }

And I have defined this directive:

    angular
        .module('myApp')
        .directive('employeeCard', function() {
            return {
                restrict: 'AEC',
                template: '<strong>{{ main.employee.name }}</strong>'
            }
    }); 

And my html:

    <body ng-controller="MainController as main">

        <employee-card></employee-card>

    </body>

By using controller as syntax, I now have to reference the alias of my controller inside the directive itself. Doesn't that pattern destroy the point of custom directives? How would I then use this custom directive inside any other controller?

Upvotes: 1

Views: 30

Answers (1)

charlietfl
charlietfl

Reputation: 171679

One way is use isolated scope and pass in employee

<employee-card employee="main.employee"></employee-card>

JS

angular
    .module('myApp')
    .directive('employeeCard', function() {
        return {
            restrict: 'AEC',
            scope: {employee :'='},
            template: '<strong>{{ employee.name }}</strong>'
        }
}); 

Upvotes: 5

Related Questions