2016-09-13 42 views
0

ルート変更時にナビゲーションバーテンプレートを変更したいと考えています。角度1.5のディレクティブ付き動的テンプレートURL

私は2つの解決策を思いつきましたが、どちらも100%満足していません。

1)私はビューの外側にng-includeを定義できます。

angular.module('automatclubApp') 
    .directive('navbar', function (PartialsPath) { 
    return { 
     restrict: 'E', 
     controller: 'NavbarCtrl', 
     controllerAs: 'navCtrl' 
    }; 
    }) 
    .controller('NavbarCtrl', function(PartialsPath, $scope, $location) { 
    $scope.$on('$locationChangeSuccess', function(/* EDIT: remove params for jshint */) { 
     var path = $location.path(); 
     //EDIT: cope with other path 
     $scope.templateUrl = (path==='/') ? '../scripts/directives/partials/navbar.html' : '../scripts/directives/partials/navbar_lobby.html'; 
    }); 
    }); 

そして私のインデックスにこれを含める:

<body> 
    <div ng-controller='NavbarCtrl'> 
     <div ng-include='templateUrl'></div> 
    </div> 
    <div ng-view=""></div> 
</body> 

2)私の見解/ main.htmlをファイルで、私は含めることができ、このようにNGを-含ま:

<ng-include src="'../scripts/directives/partials/navbar.html'"></ng-include> 

理想的には、少し洗練されたコードのためのng-viewでのディレクティブ宣言が大好きです。助言がありますか?それは私のnavbarコントローラは、私がng-viewでそれを行うことができるときには定義されていないと言います。それは、私が意図したように解決策1が動作しないように見える理由です。

+2

は役に立ちそれです::次のようにビューに呼び出すことができ

angular.module('automatclubApp') .controller('NavbarCtrl', function($scope, $location) { // $scope.myTemplate = '<span class="custom-tpl" style="color: white"> my template </span>'; $scope.getTemplateUrl = function() { var path = $location.path(); return path ==='/' ? '../scripts/directives/partials/navbar.html' : '../scripts/directives/partials/navbar_lobby.html'; }; }) .directive('navbar', function ($compile) { return { restrict: 'E', template: '<ng-include src="getTemplateUrl()">' }; }); 

機能(...を){... }}? –

+0

これは$ scopeと言っていますが、$ onはそのロジックをちょうどテンプレートに移そうとすると関数ではありません。 – Tulun

+0

http://stackoverflow.com/questions/25341641/how-to-use-a-scope-in​​-directive-templateも同様の質問です。 –

答えて

0

私は満足しています。

指令:あなたはディレクティブのparam `テンプレートを使用するため

<div ng-controller='NavbarCtrl'> 
    <navbar></navbar> 
</div> 
関連する問題