【问题标题】:Angular controller extending角度控制器扩展
【发布时间】:2015-01-26 06:41:55
【问题描述】:

我正在关注该网站上的教程:http://digital-drive.com/?p=188,让我使用extend 方法使其能够创建父/子控制器。一切似乎都很好,除了一件事——实例方法和属性。我的代码是用this approach 组织的,它或多或少看起来像这样:

test_mixin.coffee

(->
  app = angular.module("myApp.mixins")
  app.controller "myApp.mixins.TestMixin", [
    "$scope"
    ($scope) ->

      _this = this

      @notWorkingVar    = "It's not working"
      $scope.workingVar = "It's working!"
  ]
)

controller.coffee

(->
  app = angular.module("myApp.components.MyComponent")
  app.controller "myApp.components.MyComponent.Controller", [
    "$scope"
    "$controller"
    ($scope, $controller) ->

      _this = this

      # Extends
      angular.extend this, $controller('myApp.mixins.TestMixin', {
        $scope: $scope })

      # Not working examples:
      console.log _this.notWorkingVar
      console.log this.notWorkingVar
      console.log @notWorkingVar

      # Working example:
      console.log $scope.workingVar
  ]
)

基本上,附加到$scope 的东西可以正常工作。但其余的都失败了。有人知道这里出了什么问题,我该如何解决?谢谢

【问题讨论】:

    标签: javascript angularjs coffeescript


    【解决方案1】:

    将您的代码作为标准 JavaScript 放入 JSFiddle 我无法重现您的问题,并且在 TestMixin 上设置的值在运行时显示在“myApp.components.MyComponent.Controller”中。

    请参见此处的示例: http://jsfiddle.net/j6arq9z5/3/

    var app = angular.module("myApp.mixins", []);
    
    app.controller("myApp.mixins.TestMixin", function($scope) {
          _this = this
    
          this.notWorkingVar    = "It's not working"
          $scope.workingVar = "It's working!"
    });
    
      app.controller("myApp.components.MyComponent.Controller", function($scope, $controller) {
          _this = this
    
          angular.extend(this, $controller('myApp.mixins.TestMixin', {
            $scope: $scope }));
    
          console.log(_this.notWorkingVar);
          console.log(this.notWorkingVar);
    
          console.log($scope.workingVar);
      });
    

    【讨论】:

      猜你喜欢
      • 2017-01-12
      • 1970-01-01
      • 2019-08-20
      • 2011-12-29
      • 2013-05-23
      • 2012-01-05
      • 2015-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多