【问题标题】:Adding a JS Variable to a AngularJS Directory?将 JS 变量添加到 AngularJS 目录?
【发布时间】:2016-05-15 12:15:34
【问题描述】:

我似乎无法让以下代码工作:

<script>alert(topic);</script> <!-- Outputs: "dynamics" -->

<div ng-include="'content/' + topic + '.html'"></div> <!-- Does not work. -->

我推断变量是问题所在,因为以下代码确实有效:

<div ng-include="'content/' + 'dynamics' + '.html'"></div> <!-- Works. -->

有人知道我该怎么做吗?

更新:

按照 Steffen 的链接,我编写了以下代码,但仍然没有运气:

<script>
    alert(topic); // Outputs "dynamics"

    var app = angular.module('myapp', []);

    app.controller('MainCtrl', ['$scope', '$window', function ($scope, $window) {
        $scope.topic = $window.topic;
    }]);
</script>

<div ng-app="myapp" ng-controller="MainCtrl" ng-include="'content/' + 
    topic + '.html'"></div>  <!-- Does not work. -->

谢谢。

【问题讨论】:

  • 请从 ng-include 属性中删除花括号
  • 在 html 中使用这个:&lt;div ng-app="myapp" ng-controller="MainCtrl" ng-include="'content/{{topic}}.html'"&gt;&lt;/div&gt; OR &lt;div ng-app="myapp" ng-controller="MainCtrl" ng-include="'content/' + topic + '.html'"&gt;&lt;/div&gt;
  • 很抱歉,这两个都不适合我。
  • 试试这个:jsfiddle.net/ursujuge/1 您可以在浏览器的网络控制台中看到它正在尝试加载 dynamics.html

标签: javascript angularjs directory angularjs-ng-include


【解决方案1】:

基于 Steffen 的 jsfiddle,以下是我将 JavaScript 变量传递给 AngularJS 并将其用于定义目录的方式:

<script>
    // Create module.
    var app = angular.module('app', []);

    // Add controller to module.
    app.controller('MainCtrl', ['$scope', '$window', function ($scope, $window) {
        $scope.topic = $window.topic;
        console.log($scope.topic);
    }]);
</script>

<div ng-app="app" ng-controller="MainCtrl" ng-include="'content/' + 
    topic + '.html'"></div> <!-- Works! -->

非常感谢大家的回答。 :)

【讨论】:

    【解决方案2】:

    试试这个:

    <div ng-include="'content/{{topic}}.html'"></div>
    

    angularjs 中,使用 double curly brace notation {{ }} 在 HTML 中作用域 variable are access

    【讨论】:

    • 主题是在你的控制器中定义的吗??如果没有,请在您的控制器中尝试$scope.topic = topic ;
    • 不,由于我是 AngularJS 的新手,我现在正在尝试解决这个问题。如果我不能让它工作,我会发布更新。
    • 在你的控制器中尝试$scope.topic = topic ;$scope.topic = $window.topic;
    • 正确的大括号语法是 &lt;a ng-href="content/{{topic}}.html"&gt; 但据我所知 ng-include 需要问题代码中使用的 javascript 表达式。主题更有可能不是@p2 的范围变量。提到。
    【解决方案3】:

    尝试如下:

    <ng-include src="topic"> </ng-include>
    

    确保你已经定义了$scope.topic = "whateveryouwant";

    -----------或------------

    你可以这样做:

    <ng-include src="getTopic()"></ng-include>
    

    控制器:

    function AppCtrl ($scope) {
      $scope.getTopic= function () {
          return 'partials/whatever.html';
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-05
      • 2015-09-25
      • 2014-10-23
      • 2023-03-14
      • 1970-01-01
      • 2012-02-13
      • 2014-12-19
      • 2017-01-28
      相关资源
      最近更新 更多