使用"控制器实例化控制器为"语法通过$ compile,该属性的确切发布在哪里?

时间:2015-03-14 09:08:04

标签: angularjs angularjs-scope

当我使用“controller as”语法并使用$compile实例化控制器时,我试图找出控制器对象的确切发布位置。这是我的测试:

describe('"Controller as" syntax', function() {
  it('should work when controller is instantiated via $compile', function() {
    var $injector = angular.injector(['ng', function($controllerProvider) {
      $controllerProvider.register('DummyController', function() {
        this.message = 'hello there';
      });
    }]);    

    var $compile = $injector.get('$compile');
    var $rootScope = $injector.get('$rootScope');
    var $scope = $rootScope.$new();

    var view = $compile(
    '<div ng-controller="DummyController as dummy">{{dummy.message}}</div>'
    )($scope);

    $rootScope.$apply();

    // OK - The view is updated
    expect(view.text()).toBe('hello there');

    // FAIL - 'dummy' is not available on the $scope
    expect($scope.dummy.message).toBe('hello there');
  });
});

请看最后的期望。我希望通过dummy可以使用$scope,但它似乎并不存在。我错了,不应该像这样工作吗?

我还发现它可以通过$scope.$$childTail$scope.$$childHead获得:

    // OK - 'dummy' is available here
    expect($scope.$$childTail.dummy.message).toBe('hello there');

    // OK - 'dummy' is available here
    expect($scope.$$childHead.dummy.message).toBe('hello there');

这是否意味着在我的案例中创建了子范围,并且dummy仅在该子范围上发布?

1 个答案:

答案 0 :(得分:0)

来自$compile docs

  

范围

     

如果设置为 true ,则会为此指令创建新范围。

来自ngController.js

var ngControllerDirective = [function() {
  return {
    restrict: 'A',
    scope: true,
    controller: '@',
    priority: 500
  };
}];

所以,这是预期的,我的期望是错误的。获取dummy属性的唯一方法是通过那些不属于公共API的$$...内容。

相关问题