1

我正在努力使角度指令与controllerAs一起工作。使用 $scope 时,一切都按预期工作,但是当摆脱 $scope 指令时,控制器不起作用。请参阅下面的代码和 plunker:http ://plnkr.co/edit/o3F4lUrxL4mK1DWSYsad 。为什么单击按钮时不显示该值?

<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'
            }
        }
    });
4

1 回答 1

3

应该是: 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'
      }
    }
  });

刚刚更改了“vm.datasource.somekey”

于 2017-05-25T09:55:21.897 回答