gpt4 book ai didi

javascript - AngularJS;模型数据未在 html 表中列出

转载 作者:行者123 更新时间:2023-12-02 14:58:58 24 4
gpt4 key购买 nike

<table class = "table table-striped">
<thead>
<th>Title</th>
<th>URL</th>
</thead>
<tbody>
<tr ng-repeat="movie in movies">
<td>{{ movie.title }}</td>
<td>{{ movie.url }}</td>
</tr>
</tbody>
</table>

上面的代码是我的 html 端的样子。我在页面上看到表格,但没有来自 Controller 的数据。以下是我的 Controller 代码。我可以做什么来解决这个问题?

angular.module('clientBookApp')
.controller('MoviesCtrl', function ($scope) {
this.movies = [
{
title: 'Captain America',
url: 'https://www.captainamerica.com'
}
];
});

我尝试在 body 标记中添加 ng-controller 但没有成功。

<body ng-app="clientBookApp" ng-controller="MoviesCtrl">
<table class="table table-striped">
<thead>
<th>Title</th>
<th>URL</th>
</thead>
<tbody>
<tr ng-repeat="movie in movies">
<td>{{ movie.title }}</td>
<td>{{ movie.url }}</td>
</tr>
</tbody>
</table>
</body>

最佳答案

这只是因为this$scope不同

var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope) {
$scope.movies = [{
title: 'Captain America',
url: 'https://www.captainamerica.com'
}];
this.movies = [{
title: 'Iron Man',
url: 'https://www.ironman.com'
}];
console.log(this === $scope);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myCtrl">
<table class="table table-striped">
<thead>
<th>Title</th>
<th>URL</th>
</thead>
<tbody>
<tr ng-repeat="movie in movies">
<td>{{ movie.title }}</td>
<td>{{ movie.url }}</td>
</tr>
</tbody>
</table>
</body>

如果你想使用this,你不需要注入(inject)$scope,但你需要使用controller as语法,如下所示.

var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", [
function() {
var vm = this;
vm.movies = [{
title: 'Iron Man',
url: 'https://www.ironman.com'
}];
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myCtrl as vm">
<table class="table table-striped">
<thead>
<th>Title</th>
<th>URL</th>
</thead>
<tbody>
<tr ng-repeat="movie in vm.movies">
<td>{{ movie.title }}</td>
<td>{{ movie.url }}</td>
</tr>
</tbody>
</table>
</body>

关于javascript - AngularJS;模型数据未在 html 表中列出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35582897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com