AngularJS : access scope object from parent to child

标签 angularjs scope controller angular-ui-router

查询:想要访问Main Controller 范围对象进入 ui-view states

问题陈述:

在这里,我将根据从 API 获得的响应创建一个作用域对象 ( $scope.myVar ),该响应将适用于整个应用程序。因此,我在Main Controller中编写了一个API创建此范围对象,因为它是 parent Controller 和所有其他状态( ui-view )是 child .

[1]: /image/Fr4zK.png 在这里,我想访问 $scope.myVarui-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);
});

}]);

Fiddle example

关于AngularJS : access scope object from parent to child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43931330/

相关文章:

javascript - html页面找不到 Angular

javascript - 将值绑定(bind)到 Angular JS 中的输入

JavaScript 作用域混淆

c++ - 与范围有关的局部变量定义,C++

javascript - 使用纯 JavaScript 渲染这些 Angular2 组件

javascript - 以 Angular 加载测试图像源时出错

c++ - cpp中对象的范围

php - 如何正确管理 PHP 的用户权限?

codeigniter - 这是在 CodeIgniter 中使用 Controller 和 View 的好方法吗?

java - 在多路由 Controller 方法中确定路由