我是这个领域的新手,并且已经尝试了很长时间了。你可以在这里看到我的简单版本: https://plnkr.co/edit/YeahrG28bT2izX8gMKor?p=preview
你能告诉我为什么我的onclick在这里不起作用吗?我的按钮是2signUp
按钮,谢谢!
JS:
var app = angular.module('myApp', []);
app.controller('mainControl', function($scope) {
$scope.logged = false;
$scope.visiter = true;
var sub1 = document.getElementsByClassName("haha")[0];
sub1.onclick=function(){
$scope.logged = !$scope.logged;
}
})
HTML:
<!DOCTYPE html>
<html lang="en" ng-app='myApp'>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="MainViewController.js"></script>
</head>
<body ng-controller="mainControl">
<div ng-show="logged">
<button>1Sign Up</button>
<button>Log In</button>
</div>
<div ng-show="visiter">
<button class="haha">2Sign Up</button>
<button>Log In</button>
</div>
<div ng-show="logged">
hello
</div>
</body>
答案 0 :(得分:4)
使用Angular方式处理点击事件,当你有角度为你做工作时,不要使用任何document.getElementById()
爵士乐。
这就是你应该让角度处理的原因
数据绑定
数据绑定是一种在模型更改时更新视图的自动方式,以及每当视图更改时更新模型。这很棒,因为它从你需要担心的事情列表中消除了DOM操作。
使用Angular的ngClick
var app = angular.module('myApp', []);
app.controller('mainControl', function($scope) {
$scope.logged = false;
$scope.visiter = true;
$scope.signup = function() {
$scope.logged = !$scope.logged;
alert("ran the function");
}
})
<!DOCTYPE html>
<html lang="en" ng-app='myApp'>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="MainViewController.js"></script>
</head>
<body ng-controller="mainControl">
<div ng-show="logged">
<button>1Sign Up</button>
<button>Log In</button>
</div>
<div ng-show="visiter">
<button id="haha" ng-click="signup()">2Sign Up</button> <!-- use ngClick here! -->
<button>Log In</button>
</div>
<div ng-show="logged">
hello
</div>
</body>
</html>