@Aqsan,我会在回答中写了,因为它会太冗长的评论。
我的假设是,您必须调用$ scope。$ digest/$ apply()在您的外部代码完成其任务或可能只要感兴趣的对象vm.apidata发生变异。
重要提示:Angular期望vm.apidata是一个范围对象。简单地放在全局窗口/自己的范围不是你的标记所引用的。
window.vm.apidata!= scope.vm.apidata
如果你确实是正确更新范围的节点,您可以使用相同的范围内引用调用范围。$适用()。
但是,如果你不在下面是一些信息。 了解更多关于Scopes。
你可以注入到$ rootScope,这是你的服务的顶层根范围(供应商,工厂),控制器和指令引用。分层的兴趣同样$范围是控制器和指令相关,并且可以用隔离范围之外,可以在自定义的实现有注入从而范围对象继承(向下级联)在父子层次结构例如,在ng-repeat指令的情况下。我要给你一个骨架的控制器(为简单起见)实现,你不妨把实现连接:
var myModule = angular.module('myModule', []);
// This is a Service
// observe how you inject the root scope
// the array wrapper around the factory is for JS code minification protection which might name your parameter to something shorter and make it invalid (AngularJS-wise)
myModule.factory('retrieveService', ['$rootScope', '$q', function($rootScope, $q) {
function retrieve(){
// perhaps return a promise using the injected (light-weight) angular $q service
var deferred = $q.defer();
// Your external code can go in here for retrieval
// When your async code complete call for success
deferred.resolve(<yourapidata>);
// alternatively for error
deferred.reject(<yourerror>);
// of course you could also just set the value to the $rootScope.vm.apidata here and call $apply
$rootScope.vm.apidata = <yourapidata>;
$rootScope.$apply();
return deferred.promise;
}
return retrieve;
}]);
// This is a Controller
myModule.controller('MyCtrl', ['$rootScope', '$scope', 'retrieveService', '$q', function(rootScope, $scope, retrieveSvc, $q) {
function retrieve(){
// Your external code could go in here inside the controller too
// upon async retrieval perhaps...
$scope.vm.apidata = <yourvalue>
}
// given you take care of your async call using promises and/or callbacks
retrieveService().then(function(apidata) {
$scope.vm.apidata = apidata;
// though $scope is recommended imho, alternatively
// you could bind the vm.apidata to $rootScope (here or in your service) as well which $scope will inherit
$rootScope.vm.apidata = apidata;
});
}])
有很多东西要学/扩大和排列是巨大的,但希望这给你一个很好的大方向。 $http根据你的后端API,角度服务可能是一个不错的选择。
声明'vm'就像'var vm = {}; vm.apidata = []' – Satpal
我们能否看到您的控制器的javascript – Tom
请记住,如果您的异步数据检索代码不在Angular循环中,您必须具体调用范围$ digest/$适用于警告Angular触发脏检查更改。Angular控制着UI的整个回流,并且可能不知道外部非Angular JavaScript引入的更改。 – cbayram