角度控制器扩展

时间:2015-01-25 22:01:42

标签: javascript angularjs coffeescript

我正在关注该网站上发现的教程: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的内容效果很好。但其余的都失败了。有人知道这里有什么问题,我该如何解决?感谢

1 个答案:

答案 0 :(得分:0)

将您的代码作为标准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);
  });
相关问题