是否有在非 AngularJS 页面内初始化 AngularJS 应用程序的最佳实践方法?我正在向现有网页添加新功能,需要传入一个参数。具体来说,有一组选项卡,一个新选项卡将启动一个 Angular 应用程序,其中包含当前 session 中所需的参数。
也许可以将参数构建到 URL 中(即 URL 参数等)?
最佳答案
第一种选择
对于 Intranet 网站,我建议使用 Ajax GET 请求。这样就不需要发送数据了。它已经在页面上可用。以下是 AngularJS 教程 ( https://docs.angularjs.org/tutorial/step_05 ) 中数据的示例:
$http.get('phones/phones.html').success(function(data) {
$("div.mainContent").html = data;
$scope.phones = [
{'name': 'Nexus',
'snippet': 'Fast'}
];
});
phones.html 的内容:
<ul class="phones">
<li ng-repeat="phone in phones | filter:query | orderBy:orderProp">
<span>{{phone.name}}</span>
<p>{{phone.snippet}}</p>
</li>
</ul>
第二种选择
第二种方法是通过 GET 参数获取网页中填充的数据。
<a href="/tab.html?name=Nexus&snippet=Fast">
C# Razor 代码:
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
$scope.phones = [
{'name': '@Request.Params["name"]',
'snippet': '@Request.Params["snippet"]'}
];
<div>
<ul class="phones">
<li ng-repeat="phone in phones | filter:query">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li>
</ul>
</div>
</body>
</html>
您可以选择的所有方法
您可以使用 cookie、获取参数、发布参数、Web 存储(HTML5 功能)、Websockets(HTML5 功能,例如 SignalR),并在通过 AJAX 加载新页面时使用页面上的数据。对于 Cookie、获取、发布、Web 存储,您可以使用 HTML 链接和 AJAX。
这四个选项之间的选择取决于您需要发送的数据大小以及您是否考虑 SEO。 Get和cookie不适合大数据量。 Get、AJAX、Websockets 都不利于 SEO。 Cookie 和网络存储取决于浏览器,可能会被用户删除。
关于angularjs - 从非 AngularJS 页面将参数传递到 AngularJS 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23975818/