AngularJS:指令模板范围继承

时间:2014-12-05 23:18:32

标签: angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

使用ng-repeat将范围变量传递给指令模板的正确方法是什么?我试图迭代一组数据来渲染一些" app"包含templateUrls的元素。如果我没有在指令中设置范围:true,则模板变量为空。将ng-repeat中定义的变量传递给模板而不污染范围的正确方法是什么?

// 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>  

1 个答案:

答案 0 :(得分: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>