2016-07-29 208 views
0

我想創建具有範圍參數和ng-controler的指令。定製angularjs指令與範圍和NG控制器

這是這個指令應該是什麼樣子:

<csm-dir name="scopeParam" ng-controller="RegisteredController"> 
    <!--Here I want to have content--> 
    {{name}} 
</csm-dir> 

我已經「RegistertedController」在我的應用程序中聲明的地方。

angular.module('app') 
    .controller('RegisteredController', ['$scope', function ($scope) { 
     //$scope.name should be accessible here 
    }]); 

,我試圖申報指令:

angular.module('app') 
    .directive('csmDir', [function() { 
     return { 
      restrict: 'AE', 
      replace: true, 
      transclude: true, 
      scope: { 
       name: '=' 
      }, 
      template: '<section class="layout"><ng-transclude></ng-transclude></section>', 
      link: function (scope, element, attr, ctrl, transclude) { 
       element.find('ng-transclude').replaceWith(transclude()); 
       //here I also need scope.name parameter 
      } 
     }; 
    }); 

我得到錯誤:

Multiple directives [ngController, csmDir] asking for new/isolated scope on: <csm-dir name="scopeParam" ng-controller="RegisteredController"> 

現在,這個錯誤是相當翔實的,我得到它的角度不工作的我想在這裏。

我可以從指令中刪除「scope:{..}」參數並在控制器中定義它,但這不是我所需要的。

我需要的是基本上爲自定義指令提供ng-controller,然後爲該控制器提供額外的作用域變量。

我該如何做到這一點?

+0

會不會AngularJS組件滿足? – doge1ord

回答

0

你必須用標籤包裝你的指令並把控制器放在那裏。

<div ng-controller="RegisteredController"> 
    <csm-dir name="scopeParam"> 
     <!--Here I want to have content--> 
     {{name}} 
    </csm-dir> 
</div> 

沒有辦法在一個標籤中獲得兩個隔離範圍。

+0

是的,它會,但我想知道如果我可以包裝ng控制器指令內的另一個指令 –

+0

你可以做出有趣的事情。創建父指令並將其與控制器鏈接。 然後添加帶有require選項的子指令。並訪問控制器。可以嗎? – Vitalii