当通过 $compile 使用 "controller as" 语法实例化控制器时,属性 到底在哪里发布?
When instantiating a controller with "controller as" syntax via $compile, where exactly does the property get published?
当使用 "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
仅在该子范围上发布?
scope
If set to true, then a new scope will be created for this directive.
var ngControllerDirective = [function() {
return {
restrict: 'A',
scope: true,
controller: '@',
priority: 500
};
}];
所以,果然如此,我的预期是错误的。到达 dummy
属性 的唯一方法是通过那些 $$...
的东西,它们不是 public API.
的一部分
当使用 "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
仅在该子范围上发布?
scope
If set to true, then a new scope will be created for this directive.
var ngControllerDirective = [function() {
return {
restrict: 'A',
scope: true,
controller: '@',
priority: 500
};
}];
所以,果然如此,我的预期是错误的。到达 dummy
属性 的唯一方法是通过那些 $$...
的东西,它们不是 public API.