AngularJS:无法访问回调函数内的作用域



下面的函数是从指令链接函数调用的。我的问题是,我无法访问函数内部的范围

function workerInit(scope) {
var data = scope.vm.graphData;
graphViewService.send(new WorkerData(data.node[0].id,2,data.node[0].currentEntity)).then(function(response){
postWorkerResponse(response);
//scope is not defined
})
nodesinQueue.push(data.node[0].id)
}

我的工厂代码

app.factory("graphViewService",['$q',function($q){
var graphViewService = {};
var worker = new Worker('./app/modules/common/graphViewWorker.js');
var defer = $q.defer();
worker.addEventListener('message', function(e) {
defer.resolve(e.data);
}, false);
return {
send : function(data){
defer = $q.defer();
worker.postMessage(data); // Send data to our worker. 
return defer.promise;
}
};
}])

我的指令代码(从原始代码中删除了不必要的函数 def(

(function () {
var app = angular.module('sureApp');
app.directive('graphView', function ($rootScope, graphViewService) {
var controller = function () {
var vm = this;
//controller code
};
var linkFunction = function (scope, elem, attrs) {
var el = angular.element(elem);
var graph = graphInit(scope, scope.vm.graphData.node[0]);
nodes = new vis.DataSet(graph.nodeList);
edges = new vis.DataSet(graph.edgeList);
var container = el.find('#network')[0];
var data = {
nodes: nodes,
edges: edges
};
network = new vis.Network(container, data, networkOptions());
networkEvents(network, scope);
new detailWindow(el, scope);
}        
function graphInit(scope, node) {
var nodeList = [];
var edgeList = [];
workerInit(scope);
scope.vm.graphChips = [];
scope.vm.graphChips.push(node.currentEntity);
nodeList.push(updateNodeStructure(node, lIcons));
return {
nodeList: nodeList,
edgeList: edgeList
}
}
function workerInit(scope) {
var data = scope.vm.graphData;
WorkerData.url = data.url;
WorkerData.requestHeaders = requestConfig.headers;
graphViewService.send(new WorkerData(data.node[0].id,2,data.node[0].currentEntity)).then(function(response){
postWorkerResponse(response);
//scope is not defined
})
nodesinQueue.push(data.node[0].id)
console.time("test");
}
function WorkerData(id, level, currentEntity){
this.url = WorkerData.url
this.requestHeaders = WorkerData.requestHeaders;
this.id = id;
this.level = level;
this.currentEntity = currentEntity;
}
//removed other function def
return {
restrict: 'E',
scope: {
graphData: '=',
detailedView: '=',
mainEntity: '='
},
link: linkFunction,
controller: controller,
controllerAs: 'vm',
bindToController: true,
templateUrl: './app/modules/common/graphView.html'
};
})
}());

谁能帮我解决这个问题?

通过添加应用功能进行检查

function workerInit(scope) {
var data = scope.vm.graphData;
graphViewService.send(new WorkerData(data.node[0].id,2,data.node[0].currentEntity)).then(function(response){
scope.$apply(function () {
postWorkerResponse(response);
//Check here able to access scope  
});
});
nodesinQueue.push(data.node[0].id)
}

最新更新