2015-12-09 79 views
0

我有以下問題:NG-重複 - 訪問索引

我有一個自定義的指令,它顯示一個或多個表,使用模板字符串中NG-重複。在每個表格內,放置了其他幾個自定義指令。我希望這些知道所使用的元素的索引,但不能設法完成。我的代碼看起來像現在這樣:

.directive('myStuffText', function ($rootScope){ 
    return { 
     restrict: 'A', 
     require: '^form', 
     replace: true, 
     scope: true, 
     template: 
     ...... 
     '<table border="1" ng-repeat="elt in myModel.newStuffList"> 
     ...... 

     '<tr>' + 
     '<td colspan="3"><div my-add-some-editor my-element-index="$index"/></td>' + 
     '</tr>' 
     '</table>', 

     link: function (scope, elt, attrs){ 
      scope.cockpitPolicyModel.newPolicyList = []; 
     } 
    }; 

}) 
從如何我嘗試,我總是返回字符串$指數或{{$指數}}在我-附加一些編輯器指令的模板函數,而不是

獨立它的價值..

編輯 - 添加嵌套指令:

.directive('myAddSomeEditor', function($rootScope){ 
    return { 
     restrict: 'A', 
     require: '^form', 
     scope: true, 

     template: function ($scope, $attr){ 


      return 
      ..... 
      '<span id="myAddSomeEditor" name="myAddSomeEditor" class="form-control" my-generic-editor '+ 
      'my-input-mapping="myModel.someText"></span>' 
      ..... 
      ; 
      } 
    }; 
}) 
+0

難道你還可以添加嵌套指令'我加,一些編輯器' – ste2425

+0

嘗試'$父$ index' – AntiHeadshot

+0

一些建議 - 如果你提供了一個模板。像上面那樣內嵌,那麼你應該使用加入,因爲它有點更好,但歸結爲個人偏好。 模板:['

', '

Hello World

', '
'] .join('') 另外 - 你應該在你的ng-repeat中使用'track by $ index',因爲它是建議的性能。 ng-repeat =「elt in myModel.newStuffList track by $ index」 – Katana24

回答

0

這可能是因爲在你的my-add-some-editor指令,你有這樣的定義在分離範圍:

myElementIndex: '@' 

這就是爲什麼你會得到你在HTML中寫的東西的字符串。

修改成:

myElementIndex: '=' 

編輯:既然你說你不使用隔離範圍,試試這個父指令:嘗試做my-element-index="{{$index}}"。而這在兒童指令的鏈接功能:

link: function (scope, elem, attr) { 
    attr.$observe('index', function(val) { 
     scope.index = val; 
    }); 
} 
+0

我試圖添加,但沒有成功......我不是隔離範圍其實 –

+0

@PetrOsipov忽略我以前的評論。請參閱編輯。 –