【问题标题】:HTML variable value not passing to app.controller attributes in html tagHTML 变量值未传递给 html 标记中的 app.controller 属性
【发布时间】:2019-10-27 19:24:39
【问题描述】:

我正在开发一个基本的学生 - 教师 Web 应用程序,我正在使用 Angular JS 构建前端。我的 JS 文件中有 2 个应用程序控制器,一个用于检索学生,另一个用于检索分配给每个学生的科目。

我在将学生 ID 作为属性 {{student.id}} 传递给应用程序控制器时遇到问题,因为它只是作为字符串“{{student.id}}”传递而不是传递实际值{{student.id}}

出现问题的 html 代码片段

<div ng-controller="studentController" class="container">

    <table class="table">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Subjects</th>
        </tr>
        <tr ng-repeat="student in students">
            <td id>{{student.id}}</td>
            <td>{{student.Name}}</td>
            <td ng-controller="subjectController"
                id = {{student.id}}>
             {{subjects}}
            </td>
        </tr>
    </table>

我遇到的问题就在这一行

<td ng-controller="subjectController" id = {{student.id}}> {{subjects}}</td>

像这样运行同一行代码似乎可以按预期工作,但我希望能够在 for 循环中遍历所有学生 ID

<td ng-controller="subjectController" id = 1> {{subjects}}</td>

有没有人对我如何克服这个问题有任何建议。我在网上广泛查找,但找不到解决方案,因为大多数教程和文档都侧重于通过 ng-model 接收用户输入。

我对编程相当陌生,因此我们将不胜感激。

更新

app.controller('studentController', function($scope, $location, $http) {
    $http.get('http://localhost:8080/getStudents')
    .then(function(response) {
        $scope.students = response.data;
    });

});

app.controller('subjectController', function($scope, $attrs, $location, $http) {
    $http.get('http://localhost:8080/getSubjects?ID='+ $attrs.id)
            .then(function(response) {
                $scope.subjects = response.data;
            });

});

【问题讨论】:

  • 对于一个 &lt;td&gt; 元素需要一个 AngularJS 控制器似乎很奇怪。如果您坚持这样做,请出示该控制器的代码,以便我们为您提供帮助。

标签: javascript html angularjs web-frontend


【解决方案1】:

subjectController 应该从其父作用域继承属性:

app.controller("subjectController", function($scope) {
    console.log($scope.student.id); 
    console.log($scope.students); //Inherited from parent scope
});

有关详细信息,请参阅

【讨论】:

  • 谢谢一百万!这正是我想要达到的目标。我的方法完全失败了,因为我没有利用对 JS 文件中父范围的访问。
猜你喜欢
  • 2019-05-26
  • 2017-10-14
  • 1970-01-01
  • 1970-01-01
  • 2015-07-11
  • 1970-01-01
  • 2019-09-13
  • 1970-01-01
  • 2022-12-19
相关资源
最近更新 更多