Search code examples
javascriptangularjsangularjs-directiveangularjs-scope

Why isolated scope "&" is not working with controllerAs in directive of angularJs


index.html

<div ng-app="phoneApp">
  <div ng-controller="ctrl as AppCtrl">
    <div phone dial="ctrl.callHome('called home!')"></div>
  </div>
</div>

app.js :

var app = angular.module('phoneApp', []);

app.controller("AppCtrl", function ($scope) {
  var ctrl = this;
  ctrl.callHome = function (message) {
    alert(message);
  };
});

app.directive("phone", function () {
  return {
    scope: {},
    bindToController : {
      dial: "&"
    },
    controller       : controller,
    controllerAs     : 'controllerVM',

    templateUrl : 'node.html'
  };

  function controller(){
    controllerVM.onClick = function(){
      controllerVM.dial();
    }
  }
});

node.html :

<button ng-click="controllerVM.onClick()">Button</button>

when i click on Button of phone directive, it should call the function callHome of AppCtrl, but it is not getting called.

When i removes controllerAs from every where and calls the directive dial function from template directly, it is working properly

So please help me what am i missing?

Thanks in advance :)


Solution

  • Your code has 2 problems. In your HTML, you are using 'ctrl as AppCtrl' which is wrong. You should use 'AppCtrl as ctrl'. The second problem is within phone controller, you have not defined controllerVM. You should define it like 'var controllerVM = this;' I have inserted a working snippet below.

    var app = angular.module('phoneApp', []);
    
    app.controller("AppCtrl", function ($scope) {
      var ctrl = this;
      ctrl.callHome = function (message) {
        alert(message);
      };
    });
    
    app.directive("phone", function () {
      return {
        scope: {},
        bindToController : {
          dial: "&?"
        },
        controller       : controller,
        controllerAs     : 'controllerVM',
    
        template : '<button ng-click="controllerVM.onClick()">Button</button>'
      };
    
      function controller(){
        var controllerVM = this;
        controllerVM.onClick = function(){
          controllerVM.dial();
        }
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <div ng-app="phoneApp">
      <div ng-controller="AppCtrl as ctrl">
        <div phone dial="ctrl.callHome('called home!')"></div>
      </div>
    </div>