2015-08-31 78 views
2

我有一個指令,我正在使用跨多頁進行相同的搜索過濾。所以這個指令將會使用一個服務並且對代碼非常重視。因爲我想鏈接到一個控制器,而不是有指令內的控制器是這樣的:將指令屬性傳遞給鏈接的控制器?

.directive('searchDirective', function($rootScope) { 
    return { 
     restrict: 'E', 
     templateUrl:'searchtemplate.html', 
     controller: 'searchCtrl', 
     controllerAs: 'search' 
    }; 
}); 

我也想訪問模板中父範圍的數據,所以我不希望使用隔離範圍。

無論如何,這是我不知道該怎麼做。我的指令看起來像這樣:

<search-directive filter="foo"/> 

如何傳遞值的篩選器屬性,這樣我可以在我的控制器使用$ scope.filter或this.filter訪問它?

如果我正在使用一個隔離的範圍,它會很簡單。如果我在同一頁面中有控制器,我可以使用$ attrs。但由於我從另一個地方使用控制器,不想要一個孤立的範圍,我不知道如何獲得attrs值到控制器。

有什麼建議嗎?

回答

1

如何使用鏈接函數並將值傳遞給範圍?

return { 
     restrict: 'E', 
     templateUrl:'searchtemplate.html', 
     controller: 'searchCtrl', 
     controllerAs: 'search', 
     link: function (scope, element, attr) { 
      scope.filter = attr.filter; 
     } 
    }; 
+0

這個工作沒有我需要創建一個孤立的範圍。謝謝! –

0

searchDirective.js

angular 
    .module('searchDirective', []).controller('SearchCtrl', SearchCtrl) 
    .directive('SearchDirective', directive); 

function directive() { 
    var directive = { 
     templateUrl:'searchtemplate.html', 
     restrict: "E", 
     replace: true, 
     bindToController: true, 
     controller: 'searchCtrl as search', 
     link: link, 
     scope: { filter:'=' } // <-- like so here 
    }; 
    return directive; 
    function link(scope, element, attrs) {} 
} 

SearchCtrl.$inject = [ 
    '$scope', 
    '$filter']; 

function SearchCtrl(
    $scope, 
    $filter) { 

    /** Init SearchCtrl scope */ 
    /** ----------------------------------------------------------------- */ 
    var vs = $scope; 
    // .... 

此外,我強烈建議檢查了這個AngularJS風格指南,你如何寫你上面的指令是如何使用來做到這一點。約翰爸爸給出了一些更好的方式方法:https://github.com/johnpapa/angular-styleguide

指令: https://github.com/johnpapa/angular-styleguide#directives

控制器: https://github.com/johnpapa/angular-styleguide#controllers

+1

感謝您對款式指南的建議。我一定會檢查出來的。一直在努力組織我們的角色應用程序。 –

相關問題