2016-07-11 8 views
1
  1. 同じビューで指示を2回使用しています。
  2. 各ディレクティブでは、フィールドとulリストを持つテンプレートを呼び出します。
  3. ユーザーが何かを書くとき、私は の結果の配列を返すAPIを呼び出します。
  4. この配列は、ng-repeat(ul)でリストを表示するために使用されます。

問題: を最初にロードされるフィールド(最初のディレクティブ)で何かを書くユーザーは、呼び出されたNG-repeatが第二のディレクティブにある場合。ngModel参照の指示を複数回呼び出すビュー

<div style="padding: 20px;"> 
    <p>First directive :</p> 
    <span search-box ng-model="toto"></span> 
    <hr> 
    <p>Second directive :</p> 
    <span search-box ng-model="titi"></span> 
</div> 

myApp.directive('searchBox', [function() { 
return { 
    restrict: 'A', 
    scope: { 
     model: '=ngModel', 
    },   
    template: '' 
    +'<div>' 
    +  '<input type="text" ng-model="model" />' 
    +  '<ul style="background-color:#e1e1e1; width: 142px; padding: 15px;" ng-show="cities.length">' 
    +'   <li ng-repeat="city in cities">' 
      +'     {{city.label}}' 
    +'   </li>' 
    +  '</ul>' 
    +'</div>', 
    replace: true, 
    transclude: true, 
    link: function(scope, element, attrs, ngModel) { 

        scope.cities = []; 

        scope.$watch('model', function (newValue, oldValue) { if(newValue != oldValue && newValue.length > 0) search(newValue) }); 

        search = function(input) { 
       scope.cities = [ 
       {label: 'Paris'}, 
       {label: 'London'}, 
       {label: 'New York'}, 
       {label: 'Berlin'}, 
       {label: 'Lisbonne'} 
      ]; 
     }; 
    } 
} 

http://jsfiddle.net/hNTrv/10/

、最初のフィールドに何かを書く、結果ボックスは、2番目のフィールドの下に表示されます。なぜulはそれ自身の指令を参照していないのですか?

答えて

1

これは、ディレクティブの分離されたスコープの外側で検索機能を定義するためです。あなたのコードを動作させるために、あなたがそのようスコープで関数を定義する必要があります。

scope.$watch('model', function (newValue, oldValue) { if(newValue != oldValue && newValue.length > 0) scope.search(newValue) }); 

       scope.search = function(input) { 
      scope.cities = [ 
      {label: 'Paris'}, 
      {label: 'London'}, 
      {label: 'New York'}, 
      {label: 'Berlin'}, 
      {label: 'Lisbonne'} 
     ]; 
    }; 

あなたが関数内で分離されたスコープを使用することができないが、それは(あなたの関数定義はあなたの例のために二回呼び出されて、呼び出し元に利用できる最後のスコープを使用しています)ので、関数は2回再定義され、2番目の定義は、両方の呼び出しで使用されるディレクティブの2番目のインスタンスから独立スコープで呼び出されます。

+0

、先端のための感謝! :) –

1

$ watchの前に検索機能の宣言を移動します。私は理解してどのように

scope.cities = []; 
var search = function(input) { 
    scope.cities = [ 
     {label: 'Paris'}, 
     {label: 'London'}, 
     {label: 'New York'}, 
     {label: 'Berlin'}, 
     {label: 'Lisbonne'} 
    ]; 
}; 
scope.$watch('model', function (newValue, oldValue) { if(newValue != oldValue && newValue.length > 0) search(newValue)}); 

JSFiddle

関連する問題