查询:想要访问Main Controller
范围对象进入 ui-view
states
。
问题陈述:
在这里,我将根据从 API 获得的响应创建一个作用域对象 ( $scope.myVar
),该响应将适用于整个应用程序。因此,我在Main Controller
中编写了一个API创建此范围对象,因为它是 parent
Controller 和所有其他状态( ui-view
)是 child
.
在这里,我想访问 $scope.myVar
在 ui-view
的所有州.
到目前为止尝试过: HTML
<body ng-controller="MainController">
<div class="className">
<ui-view></ui-view>
</div>
</body>
主 Controller
app.controller('MainController', function($scope, $http) {
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
$scope.myVar = 'xyz'; // This variable i want to access into the state controller.
}, function errorCallback(response) {
});
});
状态 Controller :
app.controller('StateController', function($scope, $timeout) {
console.log($scope.myVar); // undefined (Not working)
$timeout(function() {
console.log($scope.myVar); // xyz (working)
}, 500);
});
我想访问 $scope.myVar
不使用 $timeout
服务。执行此操作的正确方法是什么?
最佳答案
您可以使用angular $q service
使用 Promise 和 $q 处理异步调用
var app = angular.module("MY_APP", []);
//Parent Controller
app.controller("MyCtrl1", [
'$scope','$q','$timeout', function($scope,$q,$timeout) {
$scope.async = function(name) {
var deferred = $q.defer();
//Async call: Use your ajax call here instead of $timeout
/*
$http.get('/someUrl')
.success(function(data) {
$scope.myVar = 'xyz';
deferred.resolve(data);
}).error(function(msg, code) {
deferred.reject(msg);
$log.error(msg, code);
});
*/
$timeout(function() {
deferred.notify('About to greet ' + name + '.');
if (name) {
deferred.resolve('Hello, ' + name + '!');
} else {
deferred.reject('Greeting ' + name + ' is not allowed.');
}
}, 1000);
return deferred.promise;
}
}]);
//Child Controller
app.controller("MyCtrl2", [
'$scope','$q', function($scope,$q) {
// call parent async method
var promise = $scope.$parent.async('Sai');
promise.then(function(greeting) {
//check your variable here
/*
console.log($scope.$parent.myVar);
*/
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
}, function(update) {
alert('Got notification: ' + update);
});
}]);
关于AngularJS : access scope object from parent to child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43931330/