如何在AngularJS中为不同的视图重用控制器?

如何在AngularJS中为不同的视图重用控制器?,angularjs,Angularjs,我正在从一个JSON请求接收对象数据,类似如下: { "slides": [ { "image": "http://lorempizza.com/380/240", "title": "Slide aa", "description": "I owe you the description" },{ "image": "http://lorempizza.com/380/240", "title": "Slide b

我正在从一个JSON请求接收对象数据,类似如下:

{
  "slides": [
    {
      "image": "http://lorempizza.com/380/240",
      "title": "Slide aa",
      "description": "I owe you the description"
    },{
      "image": "http://lorempizza.com/380/240",
      "title": "Slide bb",
      "description": "I owe you the description"
    }
  ],
  "title": "Interesting object",
  "description": "Lorem ipsum dolor sit amet consectetur."
}
我想用两种不同的观点。一个用于幻灯片,另一个用于对象的标题和描述,所有内容都在同一页上。为什么?因为我正在使用ui视图来显示它们

index.html

<div ui-view="slider"></div><!-- Here is the slider -->
<main ui-view role="main"></main><!-- Here is title and desc -->
<div ng-controller="InterestingObjectCtrl">
    <!-- Display slider -->
</div>
<div ng-controller="InterestingObjectCtrl">
    <!-- Display title and desc -->
</div>
InterestingObjectCtrl
控制器将加载两次相同的JSON,生成无用的HTTP请求

解决这个问题的正确方法或“角度法”是什么


设置标志(如
if($scope.requestAlreadyMade)return;
)肯定不会起作用

HTTP请求可能不是什么大问题,但这远远不是问题的关键

将控制器作为包装器调用,如下面的示例,将使其从网站上的每个页面加载,这甚至是最糟糕的

<div ng-controller="InterestingObjectCtrl">
  <div ui-view="slider"></div><!-- Here is the slider -->
  <main ui-view role="main"></main><!-- Here is title and desc -->
</div>

InterestingObjectCtrl.js

$scope.$on('dataloaded', function (data) {
// do what you want
});

我将被迫在网站的每个页面上加载控制器。这正是我试图避免的。@Lucio我以为您要求解决“感兴趣的ObjectCtrl控制器将加载两次相同的JSON”的问题。使用MainCtrl只能加载一次。同时,看看angular ui router解决此问题的方法:
   <div ng-controller="MainCtrl">
         <div ui-view="slider"></div><!-- Here is the slider -->
         <main ui-view role="main"></main><!-- Here is title and desc -->
    </div>
InterestingService.get()
    .success(function(data) {
      $scope.$broadcast('dataloaded', data);
    });
$scope.$on('dataloaded', function (data) {
// do what you want
});