为什么我不能在测试中创建此控制器?

时间:2015-01-15 17:26:26

标签: angularjs angularjs-controller

我有一个似乎运作良好的控制器。我需要编写测试用例,所以我在beforeEach()中添加了以下内容。 $controller被注入到beforeEach中,$rootScope来源$scope

    createController = function() {
        var x = $controller('MyCtrl', {
            '$scope': $scope
        });
        console.log(">>>>>>", JSON.stringify(x));
        return x;
    };

当我致电createController时,x会记录为{}

我检查了传入的$scope - 它看起来很好。我故意拼错了'MyCtrl'并得到了一个合理的错误信息。

什么会导致$controller对象返回一个空对象,而不是记录错误?

1 个答案:

答案 0 :(得分:1)

显示没有错误,因为您实际上没有在控制器实例上附加任何内容,所以所有内容都附加到范围。所以你得到一个空对象,因为控制器毕竟是实例化的。我在控制器实例上使用controllerAs语法或附加属性,您可以看到它们。



angular.module('app', []).controller('ctrl', function() {
  this.name = "John";
  this.getFormattedName = function() {
    return "Hi i am " + this.name

  }

}).controller('ctrl2', function($controller) {
  var ctrl = $controller('ctrl');
  console.log(JSON.stringify(ctrl));
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl as ctrl">
  {{ctrl.getFormattedName()}}
  <div ng-controller="ctrl2"></div>
</div>
&#13;
&#13;
&#13;

另请注意,使用JSON.stringify

时,并非所有内容都会被字符串化
  

JSON.stringify将值转换为表示它的JSON表示法:

     
      
  • 不保证非数组对象的属性按任何特定顺序进行字符串化。不要依赖于字符串化中同一对象内的属性排序。
  •   
  • 根据传统的转换语义,在字符串化期间将Boolean,Number和String对象转换为相应的原始值。
  •   
  • 如果未定义,在转换过程中遇到函数或符号,则省略(在对象中找到它)或将其删除为null(在数组中找到它时)。   即使使用replacer函数,也将完全忽略所有符号键控属性。
  •   

因此,只需在您的案例中使用指定的范围,因为这最终是视图模型。

var myCtrlScope = $scope.$new(); //Create a child scope, so you keep it separate
createController = function() {
    var x = $controller('MyCtrl', {
        '$scope': myCtrlScope
    });
    console.log(">>>>>>", myCtrlScope);
    return myCtrlScope ;
};
//And use myCtrlScope to access scope methods and properties attached by instantiating the controller `MyCtrl` using the `$controller` provider.
相关问题