2015-01-27 60 views
0

在这个指令:AngularJS directve链接范围的模板

(function(){ 
    var app = angular.module('hrefDirective',['productosService']); 

    app.directive('customHref', ['productosService', function(productosService) { 
     return { 
      restrict: 'EA', 
      template: '<li ng-repeat="familia in getfamilias"><p><a ng-bind="familia.name" ng-href="{{familia.href}}"></a></p></li>',   
      link : function(scope, element, attrs){ 
       productosService.getFamilias().then(function(data){ 
        scope.getfamilias = data.data; 
        for(var t in scope.getfamilias){ 
         productosService.getFinalFamilias(scope.getfamilias[t].id).then(function(result){ 
          scope.getfamilias[t].href = result.data.rows == 0 ? '#/producto' : '#/productos/{{familia.name}}'; 
         }); 
        }        
       }); 
      } 
     }; 
    }]);  
})(); 

我可不是能够呈现模板内的NG-绑定。链接里面scope.getfamilias具有这样的结构:

{id: "x", name: "xxxx", id_categoria: "x"} 

在链接,我发现了原来getfamilias通过服务对象,并使用新的服务id属性得到一个新的propierty,按向原始的getfamilias对象将其用作模板中的href,但它不起作用。

任何关于如何获得模板价值的线索?

+0

在服务调用中,然后回调为什么不检查什么是't'? – PSL 2015-01-27 00:34:43

+0

嗨,请看看我的答案。我已经做了一个尝试,试图用固定值来嘲笑你的服务的回应。它在那里工作:-)。 – 2015-01-27 01:35:57

回答

2

有代码中的一些错误,所以我会建议你使用以下命令:

app.directive('customHref', ['productosService', function(productosService) { 
     return { 
      restrict: 'EA', 
      template: '<li ng-repeat="familia in getfamilias"><p><a ng-bind="familia.name" ng-href="{{familia.href}}"></a></p></li>',   
      link : function(scope, element, attrs){ 
       productosService.getFamilias().then(function(data){ 
        // you have to make sure your data.data has a collection, I don't know your complete code, 
        // so I'm just leaving this part as it is. 
        scope.getfamilias = data.data; 

        //Use angular.forEach instead of for(x in y) 
        angular.forEach(scope.getfamilias, function(familia){ 
         productosService.getFinalFamilias(familia.id).then(function(result){ 

          // render the name here instead of using '#/productos/{{familia.name}}' 
          familia.href = result.data.rows === 0 ? '#/producto' : '#/productos/' + familia.name ; 
         }); 
        });        
       }); 

      } 
     }; 
    }]); 

我已经做了plunkr你,请看看:

http://plnkr.co/edit/FBS257ddJKTdYGVP4d7Y?p=catalogue

+0

很好的答案,可能你可以提到OPs案例中实际发生的事情,因此OP可以理解。 +1额外的努力。 – PSL 2015-01-27 01:40:01

+0

感谢您的杰出答案,它现在按预期工作 – 2015-01-27 09:58:30