实际上,我对 AngularJS 很陌生,所以我问了一些基本问题,这些问题对你们这些极客来说可能看起来很愚蠢。我对 jQuery 有点习惯,这就是为什么会出现一些困惑,因为文档也非常有限。
<!Doctype>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example12-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
</head>
<body ng-app="docsTemplateUrlDirective">
<div ng-controller="Controller as c">
<button ng-click="c.showdiv()">show</button >
<div id="d"></div>
</div>
<script>
angular.module('docsTemplateUrlDirective', [])
.controller('Controller', ['$scope', function($scope) {
this.showdiv=function(){
//do the ajax call and get the value from server
//pick the required template
//render the returned value on picked template
}
}]);
</script>
</body>
</html>
我希望每当我单击并调用 showdiv() 时,它都应该调用 ajax,获取值并将其呈现在 div(id=d) 部分的模板(例如 template.html)中
更新:1.假设我们有两个按钮。如果单击button1,那么它将选择template1.html,并为button2选择template2.html。
2.ajax 返回为 {"Name":"AnyName","Age":"25"} 像这样 在 template1.html 中绑定(bind)为
<div>
{{Name}},{{Age}}
</div>
对于button2,不同的值具有不同的模板样式。
最佳答案
更新您的 div“d”:
<div id="d" ng-include="chosenTemplate"></div>
更新按钮:
<button ng-click="c.showdiv('template1.html')">show 1</button >
<button ng-click="c.showdiv('template2.html')">show 2</button >
然后添加如下内容:
this.showdiv = function(theTemplate) {
$scope.chosenTemplate = theTemplate;
// do AJAX call using $http.get
$scope.Name = "John Smith";
$scope.Age = 25;
}
另请注意:
如上所述,您可以将 showdiv 函数添加到作用域,这样您就不必在其前面添加“c”前缀。在你的 html 中。
正如我上面提到的,您的 Controller 定义末尾缺少一个右方括号]。
关于javascript - 如何在AngularJS中动态添加模板页面并使用动态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39474352/