AngularJS:从父级到子级访问范围对象

时间:2017-05-12 07:02:23

标签: angularjs scope controller angular-ui-router

查询:想要将 Main Controller 范围对象访问 ui-view {{1} }

问题陈述:

在这里,我正在根据从适用于整个应用程序的API获取的响应创建一个范围对象(states)。因此,我在$scope.myVar中编写了一个API来创建此范围对象,因为它是Main Controller控制器而所有其他状态(parent)都是ui-view

[1]: https://i.stack.imgur.com/Fr4zK.png 此处:我想在child的所有州中访问$scope.myVar

目前已尝试: HTML

ui-view

主要控制器

<body ng-controller="MainController">
  <div class="className">
    <ui-view></ui-view>
  </div>
</body>

州控制员:

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) {        
  });
});

我想在不使用 app.controller('StateController', function($scope, $timeout) { console.log($scope.myVar); // undefined (Not working) $timeout(function() { console.log($scope.myVar); // xyz (working) }, 500); }); 服务的情况下访问 $scope.myVar 。这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以使用$parent.myVar访问parentScope

的数据

根据您的情况(异步调用),您可以添加$scope.$watch来观看父范围变量。

$scope.$watch("$parent.myVar", function(newValue, oldValue) {
  $scope.data = newValue;
)

在这里,您希望在子状态初始化时立即获取数据,您可以尝试使用resolve

$stateProvider.state({
  name: 'hello',
  url: '/hello',
  templateUrl: '...',
  resolve: {
    testData: function($http) {
      // invoke your async call here again
    }
  }
})

以下是resolve可能有用的一些问题。

答案 1 :(得分:1)

您可以使用angular $q service

使用promises和$ 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

相关问题