在 ng-repeat 中设置 angular 指令值

Set angular directive value inside ng-repeat

我正在尝试将值从 ng-repeat 设置为自定义指令。然而不幸的是,它不是在转发器内部设置值,而是在 ng 转发器之外设置它的设置值。

HTML:

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

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

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

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

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

   };
 $scope.heartCounterAction();

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

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

  </div>
  
  
 </div>

在 console.log 中,我得到的是 "d.id d.name"(字符串本身)而不是值。能否告诉我如何解决此问题?

提前致谢

您将参数绑定到作用域,那么为什么在指令中使用 $attrs.id$attrs.name 而不是 $scope.id$scope.name

您需要使用 $scope 来获取非 $attr 指令内部的值,例如

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>' 
};