【发布时间】:2015-08-19 16:23:27
【问题描述】:
我正在编译和链接具有隔离范围的指令(请注意,这是出于此问题范围之外的原因手动编译和链接):
outerElement = angular.element(domElement);
$injector = outerElement.injector();
$compile = $injector.get('$compile');
getTheIsolateScopeForMyDirectiveInstance().myProperty = 'foo'; // Pseudocode. I want myProperty to be available on the scope from inside the controller constructor function.
link = $compile(angular.element('<my-directive></my-directive>'));
// IIUC, the following line will instantiate
// the controller for the directive, injecting
// the isolate scope. I want to augment the
// isolate scope that is injected *before* it
// is injected.
// The value to augment the scope resides in
// *this* execution context.
// How can I do so?
renderedElement = link(outerElement.scope());
element.append(renderedElement);
MyDirective 有一个隔离作用域(我想扩充的那个),以及一个与之关联的控制器。
MyDirectiveController 控制器利用注入器来注入其隔离作用域。
MyDirectiveController.$inject = [ '$scope' ];
我想扩大隔离范围在注入MyDirectiveController 的实例之前,其值仅在运行时在上述代码的执行上下文中知道。
我该怎么做?
我的指令
function MyDirective() {
return {
scope: {}, // I want to augment this before it is injected into MyDirectiveController
restrict: 'E',
template: template,
controller: 'myDirectiveController',
controllerAs: 'ctrl',
replace: true,
};
}
MyDirectiveController
function MyDirectiveController($scope) {
console.log($scope.myProperty); // Should be 'foo'.
}
MyDirectiveController.$inject = ['$scope'];
如果这是不可能的,是否有另一种方法可以使控制器和/或隔离指令范围内的实例特定信息可用?
我现在能想到的唯一方法是扩大上面提供给link(outerElement.scope()) 的范围,然后在指令的隔离范围上定义= 属性。
编辑:
这就是我现在正在做的事情,myProperty 值最终出现在控制器的隔离范围的父级上:
var isolate = outerElement.scope().$new(true);
isolate.myProperty = 'foo';
renderedElement = link(isolate);
element.append(renderedElement);
鉴于此,当 MyDirectiveController 被实例化时:
function MyDirectiveController($scope) {
$scope.myProperty; // undefined
$scope.$parent.myProperty; // 'foo'
}
【问题讨论】:
标签: javascript angularjs