2015-01-27 58 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