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を myに挿入し、それを使用してコードをコンパイルする必要がありました。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']);

これは、アプリのルート DOM 要素が であることを angular に伝えている#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 に答える