如何在AngularJS中使用MVC
How to work on MVC in AngularJS
当我试图运行下面的代码时,我得到了这个错误参数'MyController' is not a function, got undefined
。
<!DOCTYPE html>
<html lang="en" ng-app>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<title>Hello world from Prateek</title>
</head>
<body>
<div ng-controller="MyController">
<h1>{{author.name}}</h1>
<p>{{author.title + ', ' + author.company}}</p>
</div>
<script>
function MyController($scope) {
$scope.author = {
'name': 'J Doe',
'title': 'Designer',
'company': 'ABC XYZ'
}
}
</script>
</body>
</html>
我想获得要显示的名称,标题和公司,而不是我得到的输出如下
{{author.name}}
{{author.title + ', ' + author.company}}
你还没有在javascript中定义任何angular应用。你可以使用创建的模块来定义你的控制器。然后你就可以从视图中访问你的控制器了。下面是一个例子:
<!DOCTYPE html>
<html lang="en" ng-app ="myApp">
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<title>Hello world from Prateek</title>
</head>
<body>
<div ng-controller="MyController">
<h1>{{author.name}}</h1>
<p>{{author.title + ', ' + author.company}}</p>
</div>
<script>
var myApp = angular.module("myApp", []); // definition of a module, you use myApp in ng-app directive in the html part so that angularJS initialize itself.
myApp.controller("MyController", function ($scope) {
$scope.author = {
'name': 'J Doe',
'title': 'Designer',
'company': 'ABC XYZ'
}
});
</script>
</body>
</html>
你应该先创建模块,然后创建控制器,像
var app = angular.module('myApp', []);
app.controller('MyController', function($scope) {
$scope.author = {
'name': 'J Doe',
'title': 'Designer',
'company': 'ABC XYZ'
}
});
在你的html中,你应该使用ng-app="module-name"
,如:
<html lang="en" ng-app="myApp">
相关文章:
- Asp.net MVC Angularjs 奇怪的延迟
- Spring MVC中的PUT方法HTTP Status 400-AngularJS
- 从mvc web api httpresponse生成csv,并通过angularjs接收下载
- AngularJS使用MVC动态获取html,附加到主体,并绑定一个控制器
- spring mvc, rest, angularJs
- AngularJS vs MVC控制器选择什么
- AngularJS, MVC.Unknown provider: $ScopeProvider <- $Scope
- Oracle ADF 与 Javascript MVC 框架(如 EmberJs 或 AngularJs)的对比
- 从ASP MVC异步加载Angularjs(AJAX)并执行它们
- 预检响应具有无效的 HTTP 状态代码 405 - AngularJS + Spring MVC
- AngularJS和Spring MVC安全性
- AngularJS Spring mvc @RequestParam
- 在 mvc 中使用 angularjs 和 restful web api 获取数据
- 使用 AngularJS 将数据发布到 MVC 控制器
- 如何在MVC中使用AngularJS上传文件
- 带有MVC的AngularJS,表格在http发布后不会刷新
- Spring MVC AngularJS - Post Redirect
- 使用AngularJS和$http.post在MVC应用程序中下载文件
- 如何从AngularJS接收Spring MVC中的混合参数
- Spring MVC AngularJS将前端与后端分开