我是AngularJS的新手,并且已经从W3Schools学习。我的问题是ng-click
无法正常工作。它反复呼唤。如果我在调用该函数一次后点击带有ng-click
的元素。如果我再次单击它,它会调用该函数两次。如果我继续单击该按钮,则会在我之前单击该元素的同时多次调用该函数。
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1 id="h12" ng-click="changeName()" style="cursor:pointer;">{{firstname}}</h1>
</div>
<script>
var count = 0;
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstname = "John";
$scope.changeName = function() {
var h12 = document.getElementById("h12").innerHTML;
alert(count);
if (count == 0) {
$scope.firstname = "Nelly";
changeNGClick(h12);
count++;
} else {
count++;
var x = "";
var div1 = document.getElementById("h12");
var align = div1.getAttribute("data-v");
alert(align);
$scope.firstname = align;
changeNGClick(h12);
}
}
return false;
});
function compile(element) {
var el = angular.element(element);
$scope = el.scope();
$injector = el.injector();
$injector.invoke(function($compile) {
$compile(el)($scope)
})
}
function changeNGClick(v) {
var el = document.getElementById("h12");
el.setAttribute("data-v", v);
compile(el);
}
</script>
<p>Click on the header to run the "changeName" function.</p>
<p>This example demonstrates how to use the controller to change model data.</p>
</body>
</html>
&#13;
这就是代码的工作方式。当我单击带有文本John的标题时,它将更改为显示Nelly。如果再次单击它,它应该更改回John。该值将保存在<h1>
代码data-v
上。如果您有任何建议,我也会感谢另一种方式。