【问题标题】:How to add template page dynamically with dynamic values in it in angularjs如何在angularjs中动态添加带有动态值的模板页面
【发布时间】:2016-09-13 15:57:21
【问题描述】:

实际上,我对 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.假设我们有两个按钮。如果单击按钮1,那么它将选择模板1.html 和按钮2 的模板2.html。

2.ajax 像这样返回 {"Name":"AnyName","Age":"25"} 在 template1.html 中具有绑定为

<div>
{{Name}},{{Age}}
</div>

对于button2不同的值,不同的模板样式。

【问题讨论】:

  • 所以模板和其中的内容都必须是动态的?还是模板总是 template.html?
  • 另外,您的控制器定义中缺少一个右方括号
  • "Pick the required template",你的意思是服务器给你回了一个id或者什么东西?服务器返回什么?顺便说一句,查看 $http 的 ajax 调用。你可能想把“this”改成“$scope”。
  • @jeffcarey,Tom:我更新了,请您提供提示/解决方案。

标签: javascript jquery angularjs


【解决方案1】:

更新你的 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 中。

正如我上面提到的,您在控制器定义的末尾缺少一个右方括号 ]。

【讨论】:

  • 感谢尝试并且效果很好。我猜/希望这可能是获取服务器端值并将其呈现在模板中的好方法。
猜你喜欢
  • 2012-07-04
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
  • 2018-06-13
  • 1970-01-01
  • 1970-01-01
  • 2016-05-19
  • 2014-02-27
相关资源
最近更新 更多