我的 AngularJS Not Working 代码缺少什么?目前,我正在尝试重构 AngularJS Working 代码。根据我的理解,this关键字相当于$ scope。另外,对于我的 AngularJS Not Working 代码,我试图理解为什么它不起作用。我见过工作代码使用这种模式。我正试图获得更多的背景。
AngularJS工作
<script>
var app = angular.module("app", []);
app.controller("ClassController", function ($scope) {
$scope.classBold = '';
$scope.classUnderline = '';
$scope.MakeBold = function () {
if ($scope.classBold.length == 0) {
$scope.classBold = 'bold';
} else {
$scope.classBold = '';
}
};
$scope.MakeUnderline = function () {
if ($scope.classUnderline.length == 0) {
$scope.classUnderline = 'underline';
} else {
$scope.classUnderline = '';
}
};
});
</script>
AngularJS无效
<script>
(function(){
angular
.module('classApp')
.controller("ClassController", ClassController);
function ClassController($scope){
var model = this;
model.classBold = '';
model.classUnderline = '';
model.MakeBold = function () {
if (model.classBold.length == 0) {
model.classBold = 'bold';
} else {
model.classBold = '';
}
};
model.MakeUnderline = function () {
if (model.classUnderline.length == 0) {
model.classUnderline = 'underline';
} else {
model.classUnderline = '';
}
};
}
})();
</script>
HTML
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
</head>
<body>
<div ng-app="classApp" ng-controller="ClassController">
<p ng-class="SpaceDelimitedClass">Write the class name to apply</p>
<input type="text" ng-model="SpaceDelimitedClass" placeholder="bold italic overline" />
<hr />
<p ng-class="{bold : makeBold, italic : makeItalic, overline : makeOverline}">Apply below style</p>
<label><input type="checkbox" ng-model="makeBold" />Bold</label>
<label><input type="checkbox" ng-model="makeItalic" />Italic</label>
<label><input type="checkbox" ng-model="makeOverline" />Overline</label>
<hr />
<p ng-class="[classBold, classUnderline]">Apply Below Class</p>
<button ng-click="MakeBold()">Make Bold</button>
<button ng-click="MakeUnderline()">Make Underline</button>
<hr />
<p ng-class="[MyStyle, {overline : setIt}]">Write or Apply CSS Class</p>
<input type="text" ng-model="MyStyle" placeholder="bold or italic or oblic" />
<label><input type="checkbox" ng-model="setIt" />Overline</label>
</div>
</body>
</html>
CSS
<style>
.bold {
font-weight:bold;
}
.italic {
font-style:italic;
}
.oblic{
font-style:oblique;
}
.underline{
text-decoration:underline;
}
.overline{
text-decoration:overline;
}
</style>
答案 0 :(得分:1)
控制器this
和$scope
不一样。在视图中使用控制器this
声明的变量(this
字段)可用作对象的字段。对象名称在controllerAs
设置中设置(例如在路由配置中设置)。例如。如果controllerAs
设置为&#39; $ ctrl&#39;您可以在视图中访问变量classBold
$ctrl.classBold