2016-03-28 38 views
0

我在嘗試將ng-repeat的值設置爲自定義指令。但不幸的是,它不是將值設置在中繼器內,而是在中繼器外設置其值。在ng-repeat內設置角度指令值

HTML:

var app = angular.module('testApp', []); 
 

 
app.controller('testController', function ($scope) { 
 

 
$scope.data = [ 
 
\t \t \t \t {"id": 1, "name": "Image Link"}, 
 
       {"id": 2, "name": "Image Upload"}, 
 
       {"id": 3, "name": "Video Link"}, 
 
       {"id": 4, "name": "Video Upload"} 
 
];  
 
\t \t 
 
}); 
 

 
app.directive('heartCounterDir', ['$http', function($http) { 
 
    
 
return { 
 
\t restrict: 'E', 
 
\t transclude: true, 
 
\t replace: true,  
 
\t scope:{ 
 
\t \t id:'=', 
 
\t \t name:'=', 
 
\t }, 
 
\t controller:function($scope, $element, $attrs){ 
 

 
\t \t $scope.heartCounterAction = function(){ \t 
 
\t \t \t 
 
\t \t \t console.log($attrs.id , $attrs.name); 
 

 
\t \t \t }; 
 
\t $scope.heartCounterAction(); 
 

 
\t }, 
 
\t 
 
\t template: '<div></div>' \t 
 
}; 
 

 
}]);
<!DOCTYPE html> 
 
<html> 
 
\t <head> 
 
\t \t <meta charset="UTF-8"> 
 
\t \t <title></title> \t 
 
\t \t <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script> 
 
\t \t \t <script src="app.js"></script> 
 
\t \t </head> 
 
\t \t 
 
\t <body> 
 
\t <div ng-app="testApp" ng-controller="testController"> 
 
\t \t <div ng-repeat="d in data"> 
 
\t \t <div> the id is : {{d.id}} and the name is : {{d.name}}</div> 
 
\t \t <heart-counter-dir id="d.id" name="d.name" > 
 
\t \t \t 
 
\t \t </heart-counter-dir> \t 
 

 
\t \t </div> 
 
\t \t 
 
\t \t 
 
\t </div>

中的console.log我得到 「d.id d.name」(字符串本身)而不是價值。請讓我知道如何解決這個問題?

由於提前

回答

1

您需要使用$scope的值等作爲

return { 
    restrict: 'E', 
    transclude: true, 
    replace: true,  
    scope:{ 
     id:'=', 
     name:'=', 
    }, 
    controller:function($scope, $element, $attrs){ 

     $scope.heartCounterAction = function(){ 

      console.log($scope.id , $scope.name); 

      }; 
    $scope.heartCounterAction(); 

    }, 

    template: '<div></div>' 
}; 
+0

感謝您的解決方案! –

0

要綁定的參數範圍,所以你爲什麼要做$attrs.id$attrs.name你的指令,而不是$scope.id$scope.name裏面?

+0

是的,你是對的不$attr內部指令。這是我的錯誤。 –