2016-11-28 69 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> 
相關問題