【问题标题】:angular directive with controllerAs dosn't work带控制器的角度指令不起作用
【发布时间】:2017-10-25 22:03:10
【问题描述】:

我正在努力使角度指令与 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'
            }
        }
    });

【问题讨论】:

  • 它可能不起作用,因为您没有在模板中使用vm.somekey,您的控制器改为定义vm.current.somekey,但仅在单击按钮后。如果您想在加载模板后显示值,您可能应该在初始化 vm 后添加 vm.somekey = 'somevalue'
  • controllerAs 概念用于减少范围的使用。因此您可以在控制器中使用 this.somekey = 'somevalue' 而不是使用 scope.somekey = 'somevalue'
  • 它只适用于@michał-sałaciński change: "vm.datasource.somekey"
  • 您好,将您的模板更改为 '
    {{vm.datasource.somekey}}
    '

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-controlleras


【解决方案1】:

应该是: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”

【讨论】:

    猜你喜欢
    • 2016-06-03
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多