我是这个领域的新手,并试图编写一些代码。以下是我的测试:
JS:
(function() {
angular.module('dashboard', []);
})();
(function() {
'use strict';
angular.module('dashboard').controller('mainControl', function() {
var self=this;
self.logged = true;
alert("hello");
});
})();
HTML:
<!DOCTYPE html>
<html lang="en" ng-app='dashboard'>
<head>
<meta charset="utf-8">
<title>Shen's Event Planner</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="all.js"></script>
<!--link rel="stylesheet" href="main.css"-->
</head>
<body ng-controller="mainControl">
<div>
<div ng-show="mainControl.logged">
<button type="button" class="btn" data-toggle="modal" data-target=".signUp">Sign Up</button>
<button type="button" class="btn" data-toggle="modal" data-target=".logIn">Log In</button>
</div>
<div ng-hide="mainControl.logged">
<button type="button" class="btn" data-toggle="modal" data-target=".createEvent">Create Event</button>
<button>Sign Out</button>
</div>
</div>
</body>
</html>
可运行的代码在这里
https://plnkr.co/edit/ci5FCx4sASTzikgpn0gb?p=preview
我运行它并给出警报,这意味着变量已设置。但无论我在js文件中将this.logged
设为false。输出完全相同。你能告诉我原因吗?谢谢!
我知道$ scope是个好主意,但我在这里测试其他方法。
答案 0 :(得分:1)
你应该使用$ scope,
(function() {
'use strict';
angular.module('dashboard').controller('mainControl', function($scope) {
$scope.logged = true;
alert("hello");
});
})();
<强> DEMO 强>
如果您使用Controller As语法,请按如下所示更改您的代码,
<body ng-controller="mainControl as mc">
<div>
<div ng-show="mc.logged">
<button type="button" class="btn" data-toggle="modal" data-target=".signUp">Sign Up</button>
<button type="button" class="btn" data-toggle="modal" data-target=".logIn">Log In</button>
</div>
<div ng-hide="mc.logged">
<button type="button" class="btn" data-toggle="modal" data-target=".createEvent">Create Event</button>
<button>Sign Out</button>
</div>
</div>
</body>