2016-11-28 76 views
1

我有一个视图与控制器名称"Listctrl"在这个视图中我想有一个不同的控制器命名为"LocationCtrl"。目前,我这样做是这样的:使用多个控制器在同一视图与离子

路由

.state('list', { 
     url: '/list', 
     templateUrl: 'templates/list.html', 
     controller: "ListCtrl", 
     cache: false 
     }) 

HTML(list.html)

<ion-view ng-init="ini()" ng-controller="LocationCtrl"> 
    <ion-header-bar class="banner-top ext-box" align-title-h="left"> 
    <div class="int-box2"><h2 id="s_back1">STORIE</h2></div> 
    </ion-header-bar> 
<ion-content class="has-header has-footer no-bgColor start" overflow-scroll="false" has-bouncing="false"> 
<div class="container-list"> 

我应该如何正确地解决这个问题?我需要两个控制器用于相同的视图,但在不同的地方,因为我想在不同的视图中重用控制器代码。

目前<ion-view ng-init="ini()" ng-controller="LocationCtrl"> 不运行LocationCtrl

任何帮助,非常感谢!

+0

这并不完全合理。 “一个观点的两个控制器”甚至意味着什么?你(或框架)如何能够区分? – Claies

回答

1

对于一个视图不可能有两个控制器,因为这没有意义。如果您有需要共享,使用控制器继承一个功能,但是这是可能的,只有LocationCtrl增加了它的方法$scope

var app = angular.module('angularjs', []); 

app.controller('LocationCtrl', function($scope) { 
    // I have functionality to share 
}); 

app.controller('ListCtrl', function($scope, $controller) { 
    $controller('LocationCtrl', {$scope: $scope}); // This adds properties to ListCtrl's scope 
}); 

另一种方法可能是把ng-controller="LocationCtrl"到包装DIV:

<ion-view ng-init="ini()"> 
    <div ng-controller="LocationCtrl"> 
     <ion-header-bar class="banner-top ext-box" align-title-h="left"> 
      <div class="int-box2"><h2 id="s_back1">STORIE</h2></div> 
     </ion-header-bar> 

但这似乎不是一个好的选择。更好的方法是创建与LocationCtrl定义的功能组件/指令,并在你看来什么地方使用它:

<ion-view ng-init="ini()"> 
    <component-with-location-ctrl-functionality></component-with-location-ctrl-functionality> 
0

如果要设置控制器“的ListCtrl”的路线,并要创建的地方与其他控制器这条路线中,你可以用隔离范围创建指令

app.directive('yourNewDrctv', function() { 
    return { 
     restrict: 'E', 
     templateUrl: 'yourNewTmpl.html', 
     scope: {}, 
     controller: 'yourNewCtrl' 
    }; 
}); 

,并在您的模板“模板/ list.html”随处 就像使用它:

<your-new-drctv></your-new-drctv> 
相关问题