我有一个控制器,在通过我的Angular自定义服务从WebApi检索数据(作为对象)后执行$broadcast()
。在$broadcast()
方法中,它从其范围传递变量。
另一方面,我的自定义指令具有隔离范围,它监听控制器的广播,并将传递的数据添加到自己的范围。
当我在指令范围内更改数据时,他们不会改变控制器的范围。
实际上,对我而言,这就是我所需要的。
但是,如果$broadcast()
将参考权复制到控制器的范围对象,为什么指令看不到它的对象?< / p>
我发现了一个类似的问题here
但它的回答是提交引用。
这是我的(TypeScript)代码:
export class FoodSetController {
//variable that will reference to scope;
private _scope: any;
...
//constructor
static $inject = ["$scope", ...];
constructor($scope: any, ...) {
...
//initialize reference to scope
this._scope = $scope;
...
//initialize scope data be passed by &broadcast()
this._scope.foodSet = null;
...
}
...
//method that broadcasts scope data after it's retrieving from API
bindFoodSet(data): void {
...
this._scope.foodSet = data;//new Object()
...
this._scope.$broadcast("foodSetLoaded", this._scope.foodSet);
}
我的自定义指令(由工厂创建):
export class FoodDiagramm implements ng.IDirective {
//scope property from ng.IDirective
public scope: boolean | Object;
...
//constructor
constructor() {
...
//create an isolated scope
this.scope = {};
...
}
//link method
public link($scope): void {
...
//add listener to isolated scope (HERE IS GOTCHA)
($scope as ng.IScope).$on("foodSetLoaded", (e: ng.IAngularEvent, foodSet: any): any => {
...
//?PASSED BY VALUE, BECAUSE DATA IN CONTROLLER'S SCOPE HADN'T BEEN CHANGED
foodSet = "zzz";
$scope.foodSet = foodSet;
});
...
}