gugol gugol - 6 months ago 18
AngularJS Question

Adding a Directive to a Controller using "Controller as" syntax

I have been learning about the kind of "new" "Controller as" syntax. While I find that the syntax is clearer for readability sometimes to do a relative simple thing it just gets more complicated, for example when adding a Directive to a Controller.

How would this simple sample be done with the "Controller As" syntax?

Plunk Sample

I tried something like this:

app.directive('myCustomer', myCustomer);

function myCustomer() {
return {
restrict: 'E',
scope:{ customer: '=info'},
//templateUrl: 'my-customer.html',
template:'Name: {{vm.customer.name}} Address: {{vm.customer.address}}',
controller: Controller,
controllerAs: 'vm',
bindToController: true
};
}


I don't quite get it to work just as the regular "$scope" syntax. Maybe I am missing something.

Note: The sample uses Angular 1.5.5

Answer

Check this fork of your plunk: https://plnkr.co/edit/7iA3JMhuUlvIQN9ORs81?p=preview

.directive('myCustomer', function() {
    return {
      restrict: 'E',
      scope: {
        customerInfo: '=info'
      },
      controllerAs: 'vm',
      controller: ['$scope', function(scope){
        console.log(scope.customerInfo);
      }],
      templateUrl: 'my-customer-iso.html'
    };
  });

UPD

code should be like so:

(function(angular) {
  'use strict';
angular.module('docsIsolateScopeDirective', [])
  .controller('Controller', ['$scope', function($scope) {
    $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
    $scope.igor = { name: 'Igor', address: '123 Somewhere' };
  }])
  .directive('myCustomer', function() {
    return {
      restrict: 'E',
      scope: {
        customerInfo: '=info'
      },
      controllerAs: 'vm',
      bindToController: true, //the  missing line!!
      controller: 'dirCtrl',
      templateUrl: 'my-customer-iso.html'
    };
  })
  .controller('dirCtrl', ['$scope', dirCtrl]);

  function dirCtrl() {
    //var vm = this; //no need in this!
}

})(window.angular);

and

 Name: {{vm.customerInfo.name}} Address: {{vm.customerInfo.name}}

in the template

Comments