javascriptangularjsangularjs-directiveangularjs-scopeangularjs-controlleras

angular directive with controllerAs dosn't work


I'm struggling with making angular directive work with controllerAs. When using $scope everything work as expected but when get rid of $scope directive controller doesn't work. Please see the code below and plunker: http://plnkr.co/edit/o3F4lUrxL4mK1DWSYsad. Why the value is not displayed on button click?

<body ng-app="myApp">
<div ng-controller="TestCtrl as test">
    <button ng-click="test.buttonClick()">push me</button>
    <test-directive  datasource="test.current"></test-directive>
</div>
</body>

angular.module('myApp', [])
    .directive('testDirective', function() {
        var controller = function() {
            console.log(this);

        };
        return {
            controller: controller,
            controllerAs: 'vm',
            bindToController: true,
            scope: {
                datasource: '=',
            },
            template: '<div>{{vm.somekey}}</div>'
        }
    })
    .controller('TestCtrl', function() {
        var vm = this,
            current = {};

        vm.buttonClick = function() {
            console.log('buttonClick');
            vm.current = {
                somekey: 'somevalue'
            }
        }
    });

Solution

  • It should be rather: PLNKR

    // Code goes here
    angular.module('myApp', [])
      .directive('testDirective', function() {
        var controller = function() {
          console.log(this);
    
        };
        return {
          controller: controller,
          controllerAs: 'vm',
          bindToController: true,
          scope: {
            datasource: '=',
          },
          template: '<div>{{vm.datasource.somekey}}</div>'
        }
      })
      .controller('TestCtrl', function() {
        var vm = this,
          current = {};
    
        vm.buttonClick = function() {
          console.log('buttonClick');
          vm.current = {
            somekey: 'somevalue'
          }
        }
      });
    

    Just changed "vm.datasource.somekey"