有人可以指出代码中的错误吗
问题 1addstudent.html 文件的保存按钮不起作用。如果使用 $Scope 那么它可以工作,但是修改了使用 ControllerAs 的代码,该功能停止工作。当在调试器工具中检查时,即使控制也没有在 addStudentController 页面的行
中进行(addCtrl.saveStudent = 函数(学生){)
点击“保存”按钮后什么也没有发生。
问题 2 在 app.js 中,当注释代码变为事件状态时,应用程序就会完全停止工作。
问题3想知道如何在addStudentController.js的取消按钮处重定向到index.html,使用window.location是个好习惯吗?
addStudentController.js
module.controller('addStudentController',
function addStudentController(){
addCtrl = this;
addCtrl.saveStudent = function(student){
window.alert(student.name+' save successfully');
};
addCtrl.cancelStudent = function(){
window.location='/index';
};
}
);
app.js
var module = angular.module('myApp',['ngRoute'])
.config(['$routeProvider', function($routeProvider){
$routeProvider
/*.when('/index', {
templateUrl: 'index.html',
controller: 'studentController',
title: 'This is index page'
})*/
.when('/addStudent', {
templateUrl:'templates/addStudent.html',
controller:'addStudentController',
controllerAs: 'addCtrl'
})
/*.otherwise({
redirectTo: '/index'
})*/;
}]);
addStudent.html
<div>
<div>
<h1>New Student</h1>
<p>
<img data-ng-src="{{student.imageUrl}}" alt={{student.name}}
height="40px">
</p>
<hr>
<form name="newStudentForm">
<fieldset>
<label for="studentName">Student Name:</label>
<input id="studentName" type="text" data-ng-model="student.name" required
placeholder="Name of student...."> <br>
<label for="studentDepartment">Student Department:</label>
<input id="studentDepartment" type="text"
data-ng-model="student.department" placeholder="Name of student Department ...."> <br>
<label for="studentBranch">Student Branch:</label>
<input id="studentBranch" type="text" data-ng-model="student.branch"
placeholder="Name of student Branch ...."> <br>
</fieldset>
<button type="submit" data-ng-disabled="newStudentForm.$invalid"
data-ng-click="saveStudent(student)">Save</button>
<button type="button" data-ng-click="cancelStudent()">
Cancel</button>
</form>
<label for="studentImage">Student Image:</label> <input
id="studentImage" type="text" data-ng-model="student.imageUrl"
placeholder="url for student image ....">
</div>
</div>
最佳答案
问题 1:在 html 中使用 addCtrl.saveStudent(student)
问题 2:您在控制台中看到异常吗?您可能没有正确注入(inject) Controller ,或者您的模板 url 可能是错误的。目前的信息很难判断。
问题3:使用定位服务:Angular location
关于javascript - AngularJS:在路由器中使用 ControllerAs 不起作用并出现 app.js 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41349991/