AngularJS中,视图(views)和模板URL(templateUrl)是用于定义页面的两种不同方式。
视图是直接将HTML代码嵌入到AngularJS的页面中,可以通过以下方式定义视图:
app.config(function($routeProvider) {
$routeProvider
.when('/', {
template: 'Hello World!
'
})
.when('/about', {
template: 'About Us
This is the About page.
'
})
.otherwise({
redirectTo: '/'
});
});
在上面的代码中,视图被定义为直接嵌入在template
属性中的HTML代码。
另一种方式是使用模板URL(templateUrl),它允许我们将HTML代码保存在外部文件中,然后通过URL进行引用。可以通过以下方式定义模板URL:
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html'
})
.when('/about', {
templateUrl: 'views/about.html'
})
.otherwise({
redirectTo: '/'
});
});
在上面的代码中,模板URL被定义为指向外部HTML文件的URL。
使用模板URL的优势是可以将HTML代码与JavaScript代码分离,使代码更清晰和易于维护。
总结一下,视图直接嵌入HTML代码,而模板URL通过URL引用外部的HTML文件。