[英]Weird behavior of my controller variables
我是該領域的新手,正在嘗試編寫一些代碼。 以下是我的測試:
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 this.logged
為true。 輸出都是一樣的。 你能告訴我原因嗎? 謝謝!
我知道$ scope是個好主意,但是我在這里測試其他方法。
您應該使用$ scope,
(function() {
'use strict';
angular.module('dashboard').controller('mainControl', function($scope) {
$scope.logged = true;
alert("hello");
});
})();
如果您使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.