1

我正在使用 AngularJS 编写我的第一个应用程序,但我被困在某个需要跨不同控制器共享数据的地方。

我有这样的事情:

function ctrl1 ($scope) {
  $scope.data = new Object();
}

function ctrl2 ($scope, $http) {
  $http.get('my_page').success(function(html) {
    // I set some values to the parent's data object
    $scope.data['my_key'] = 'My value';
    // The html loaded here contains a ng-controller='ctrl3' somewhere
    $('#mydiv').html(html);
    // So I bootstrap it
    angular.bootstrap($('#mydiv'), ['my_module']);
  });
}

// Is not a child of ctrl2, but is a child of ctrl1
function ctrl3 ($scope) {
  $scope.my_key = $scope.data.my_key; // Cannot read property 'my_key' of undefined 
  // And in an ng-repeat where I want to display my_key, nothing is shown. 
  // However, if I manually set my_key here, everything is displayed correctly.
  // So the controller and ng-repeat are correctly parsed after bootstrapping
}

这是 HTML:

<div ng-controller="ctrl1">
  <div ng-controller="ctrl2">
    <!-- some content -->
  </div>
  <!-- some more code -->
  <div id="myDiv">
    <!-- currently empty, will be added html with AJAX, ang ng-controller="ctrl3" is in this (as well as my ng-repeat) -->
  </div>
</div>

根据这个非常好的答案data,如果它没有在子范围中设置并且在父范围中设置,我应该能够读取和设置属性。

为什么这不起作用?

[编辑]

现在想通了,这是解决方案。在将其添加到 DOM 之前,我必须将$compile注入我的并用它编译代码。ctrl2

function ctrl2 ($scope, $http, $compile) {
  $http.get('my_page').success(function(html) {
    // I set some values to the parent's data object
    $scope.data['my_key'] = 'My value';
    // The html loaded here contains a ng-controller='ctrl3' somewhere
    // ** Have to compile it before appending to the DOM
    $('#mydiv').html($compile(html)($scope));
  });
}
4

2 回答 2

2

您在这里看到的问题不是范围继承,问题是您调用angular.bootstrap

angular.bootstrap($('#myDiv'), ['my_module']);

这告诉 Angular 应用程序的根 DOM 元素是#myDiv,因此您的ng-controller="ctrl1"ng-controller="ctrl2"不被视为该应用程序的一部分。因此,您不会得到预期的结果。

使固定:

<div id="myContainer" ng-controller="ctrl1">
  <div ng-controller="ctrl2">
    <!-- some content -->
  </div>
  <!-- some more code -->
  <div id="myDiv">
    <!-- currently empty, will be added html with AJAX, ang ng-controller="ctrl3" is in this (as well as my ng-repeat) -->
  </div>
</div>

在 JS 中:

angular.bootstrap($('#myContainer'), ['my_module']);
于 2013-08-06T17:38:21.873 回答
1

您可以构建某种服务助手,也可以使用内置的$on$broadcast在范围之间传递数据。

例如设置和传递数据

$scope.functionName = function () {
 $scope.message = "This is a message, string, object or whatever";
 $rootScope.$broadcast('message', message);
};

在另一个控制器中捕获广播

    $scope.$on('message', function(message){
     $scope.message = message;

     // You now have access to message 
   });

有一种更优雅的方法可以做到这一点,所以你不必污染$rootScope,但我现在不记得该怎么做了。

添加了示例。http://jsfiddle.net/vPq2P/3/

于 2013-08-06T15:32:10.600 回答