我写了一个角度代码来实现Like并删除Like功能。为此,我使用了一个指令“like-directive”,它带有三个函数 1. upFn:喜欢时要执行的代码 2. downFn:删除时要执行的代码 3. upvChk:检查是否喜欢的功能。我用假
开始了出于某种原因,我无法使用ng-if变量。我必须使用upvChk函数。但是这个函数被调用了两次以上。它应该只调用两次因为我使用ng-if两次。
以下是codepen链接http://codepen.io/puneet27/pen/jApJww/
angular.module('app',[])
.controller('MainCtrl',['$scope',MainCtrl])
.directive('likeDirective',[likeDirective]);
function MainCtrl($scope){
var mcl = this;
mcl.checkUpvoted = checkUpvoted;
mcl.upvote = upvote;
mcl.downvote = downvote;
function checkUpvoted(){
alert("function to check whether liked or not");
return mcl.upvoted;
}
function upvote(){
alert('like completed');
mcl.upvoted = true;
}
function downvote(){
alert('dislike completed');
mcl.upvoted = false;
}
}
function likeDirective(){
return {
restrict: 'E',
scope: {
upFn:'&upFn',
downFn:'&downFn',
upvChk:'&upvChk'
},
templateUrl: 'tpl.html'
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MainCtrl as mc">
<like-directive up-fn="mc.upvote()" down-fn="mc.downvote()" upv-chk="mc.checkUpvoted()"></like-directive>
</div>
<script type="text/ng-template" id="tpl.html">
<div><span id="upvote" ng-if="!upvChk()" ng-click="upFn()">Like</span><span id="upvoted" ng-if="upvChk()" ng-click="downFn()">Liked</span></div>
</script>
</div>