【问题标题】:Set angular directive value inside ng-repeat在 ng-repeat 中设置角度指令值
【发布时间】:2016-07-15 16:55:35
【问题描述】:

我正在尝试将值从 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”(字符串本身)而不是值。请告诉我如何解决这个问题?

提前致谢

【问题讨论】:

    标签: angularjs angularjs-directive ng-repeat


    【解决方案1】:

    您需要在指令中使用$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>' 
    };
    

    【讨论】:

    • 感谢您的解决方案!
    【解决方案2】:

    您将参数绑定到范围,那么为什么要在指令中使用 $attrs.id 和 $attrs.name 而不是 $scope.id 和 $scope.name?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-07
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多