0

使用ng-repeat將範圍變量傳遞到指令模板的正確方法是什麼?我試圖迭代一組數據來呈現一些包含templateUrls的「app」元素。如果我沒有在指令中設置scope:true,模板變量是空的。將ng-repeat中定義的變量傳遞給模板而不污染範圍的正確方法是什麼?AngularJS:指令模板範圍繼承

// controller 
userApp.controller('mainController', ['$scope', 'mainFactory', 'credsFactory', 
function($scope, mainFactory, credsFactory) { 

    var findAppsData = function() { 

     mainFactory.findAppsData() 
      .success(function (data) { 
       $scope.appsData = data; 
      }). 
      error(function(error) { 
       $scope.status = 'Unable to get data: ' + error.message; 
      }); 
    }; 

    findAppsData(); 

}]); 


// directive 
userApp.directive('app', function(){ 
    return { 
     restrict : "E", 
     scope : {}, // vars referenced in template are empty. 
     scope : true // vars are inherited in template. 
     templateUrl : 'templates/app-detail.html' 
    } 
}) 

// index.html 
<app ng-repeat="app in appsData"></app> 

// app-detail.html 
<span class="rtl">{{ app.appDisplayName }}</span> 
<span class="rtl">&nbsp;|&nbsp;{{ app.categoryId }}</span> 
<br /> 
<span class="rtl">{{ app.description }}</span> 
+0

這個答案的工作:http://stackoverflow.com/questions/18600710/angularjs-ng-repeat-with-custom-element-inside-a-table-is -rendering,奇怪 – neridaj 2014-12-06 00:33:01

回答

0

工作液:http://plnkr.co/edit/QfTQao?p=preview

你需要使用鏈接功能等待中,當他們編譯得到傳遞的變量,以及編譯的吧。

嘗試這樣:

// directive 
userApp.directive('app', function($compile){ 
    return { 
     // staying away from E, IE doesn't like custom elements 
     restrict : "A", 
     scope : { 
      app: '=' 
     }, 
     link: function(scope, element, attrs) {   
      var delWatch = scope.$watch('app', function(newVal, oldVal) { 

      // wait for scope.app to load 
      if(scope.app === undefined) return; 

      var template = ''; 
      template += '<span class="rtl">{{ app.appDisplayName }}</span>'; 
      template += '<span class="rtl">&nbsp;|&nbsp;{{ app.categoryId }}</span>'; 
      template += '<br />'; 
      template += '<span class="rtl">{{ app.description }}</span>'; 

      element.html(template); 
      $compile(element.contents())(scope); 

      // remove watcher 
      delWatch(); 
      }); 
     } 
    } 
}); 

// index.html 
<div ng-repeat="app in appsData"> 
    <div app="app"></div> 
</div>