我正在为我的指令创建一个工具提示,但不管怎样,要么全部四个都会出现,要么在绿色div中没有点击。让我知道我在这里做错了什么。
工作Plnkr - https://plnkr.co/edit/Rk2hMz6gmKPlN3IhKMYE?p=preview
HTML -
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Test</title>
<link rel="stylesheet" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="mainCtrl">
<div class="con-div" ng-repeat="row in fakeDataSet" ng-click="data.clicked = !data.clicked">
<test-div click-val="data.clicked"></test-div>
</div>
</body>
</html>
JavaScript -
var myApp = angular.module('myApp', []);
myApp.controller('mainCtrl', function($scope){
$scope.fakeDataSet = [1,2,3,4];
$scope.data = {};
$scope.data.clicked = false;
});
myApp.directive('testDiv', function(){
return {
restrict: 'EA',
scope: {
clickVal: "="
},
link: function (scope, element, attrs){
console.log("clickVal", scope.clickVal);
},
template: '<div class="tooltip" ng-if="clickVal">This is a tooltip</div>'
};
})
答案 0 :(得分:2)
您将指令的所有4个实例绑定到同一范围。这样的事情将为每个实例创建一个单独的状态。如果将click事件绑定到一个函数,它会在设置active之前重置所有truthy / falsys,它只会保持一个打开。
<div class="con-div" ng-repeat="row in fakeDataSet" ng-click="setToolTip(row)">
<test-div click-val="data.clicked[row]"></test-div>
</div>
$scope.fakeDataSet = [1,2,3,4];
$scope.data = {};
$scope.data.clicked = {1: false, 2: false, 3: false, 4:false};
$scope.setToolTip = function(row){
Object.keys($scope.data.clicked).forEach(function(elem){
$scope.data.clicked[elem] = false;
});
$scope.data.clicked[row] = true;
}
答案 1 :(得分:0)
您只需将其更改为:
ng-click="data.clicked[row] = !data.clicked[row]">
答案 2 :(得分:0)
看起来你已经为每个元素绑定了相同的点击值,因为所有工具提示都显示/隐藏在一起。
<div class="con-div" ng-repeat="row in fakeDataSet" ng-click="row.clicked = !row.clicked">
<test-div click-val="row.clicked"></test-div>
</div>
$scope.fakeDataSet = [{value : 1, clicked : false},
{value : 2, clicked : false},
{value : 3, clicked : false},
{value : 4, clicked : false}];