【问题标题】:Using "this" instead of "scope" with AngularJS controllers and directives在 AngularJS 控制器和指令中使用“this”而不是“scope”
【发布时间】:2014-08-12 14:12:15
【问题描述】:

我最近在阅读 John Papa 的固执己见的 AngularJS style guide 并注意到他关于控制器的约定:

/* recommended */
function Customer () {
  var vm = this;
  vm.name = {};
  vm.sendMessage = function () { };
}

当它在控​​制器中使用时,它工作得很好,因为你可以做这样的事情(他的例子):

<!-- recommended -->
<div ng-controller="Customer as customer">
    {{ customer.name }}
</div>

但是,我对它如何与依赖此控制器的指令一起工作感到更加好奇。例如,在我的控制器上使用$scope,我可以这样做:

testModule.directive("example", function(){
    return{
        template: "Hello {{customer}}",
        controller: "exampleCtrl"
    }
});
testModule.controller("exampleCtrl", exampleCtrl);
function exampleCtrl($scope){
    $scope.message = "Display this";
}

但我无法使用this.message

testModule.directive("example", function(){
    return{
        template: "Hello {{customer}}", //Doesn't work!
        controller: "exampleCtrl"
    }
});
testModule.controller("exampleCtrl", exampleCtrl);
function exampleCtrl(){
    var vm = this;
    vm.message = "Display this";
}

所以我的问题是, 这在指令中如何工作?我试过使用:

{{customer}}
{{this.customer}}
{{exampleCtrl.customer}}

没有任何工作。如您所见,我在黑暗中拍摄,并没有真正理解差异以及如何在 Angular 中使用 this 而不是 scope。此外,由于这不是惯例,我无法找到很多与它相关的资源,因为它比 Angular 更能理解 JS。

感谢任何帮助!

【问题讨论】:

    标签: javascript angularjs angularjs-scope


    【解决方案1】:

    使用此样式时,指令应根据Directive 文档在其返回对象中使用controllerAs 属性。

    你的指令最终看起来像:

    testModule.directive("example", function() {
        return {
            template: "Hello {{controller.customer}}",
            controller: "exampleCtrl",
            controllerAs: "controller"
        };
    });
    

    【讨论】:

    • 太容易了,应该深入研究文档。谢谢!
    • 感谢您的回答...我将添加注释以将其添加到我的样式指南中。我可能应该已经拥有它了:)
    • 将此添加到我的 angularjs 样式指南 github.com/johnpapa/angularjs-styleguide/commit/…
    • 孤立作用域的概念呢?
    【解决方案2】:

    我相信controller: 'exampleCtrl as controller' 也可以。我应该确认一下,但我今天早上太懒了?

    【讨论】:

      猜你喜欢
      • 2017-05-02
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多