Hello Guys我是AngularJS的学习者。我有这个问题。我想问你为什么它没有向HTML页面显示数据。当我按F12时,它没有显示任何错误...为什么我不能为变量$ scope = students设置数据? 有人可以向我解释原因吗?非常感谢:)
<div id="angularController" data-ng-controller="firstCtrl" data-ng-app="app">
<table>
<tbody>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
University
</th>
<th>
Gender
</th>
</tr>
<tr data-ng-repeat="student in students">
<td>
{{student.id}}
</td>
<td>
{{student.name}}
</td>
<td>
{{student.university}}
</td>
<td>
{{student.gender}}
</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
var str;
$(document).ready(function () {
str = '{"id":"1","name":"Nang Thang Hai","university":"Hutech University","gender":"true"},{"id":"2","name":"Gio Thang Chin","university":"Foreign Trade University","gender":"false"}';
angular.element('#angularController').controller().doSomthing(str);
//angular.element('#angularController').controller()
});
var app = angular.module('app', []);
app.controller('firstCtrl', function ($scope) {
//$scope.students = json = $.parseJSON('[' + str + ']');
$scope.doSomthing = function (str) {
json = $.parseJSON('[' + str + ']');
alert(json[0].name);// it shows data here:Bui Vuong Khanh
$scope.students = json;//is it right ?
};
return {
doSomthing: $scope.doSomthing
};
});
</script>
答案 0 :(得分:1)
如果可能,我永远不会推荐它,但问题是当您从摘要周期之外更新范围值时,angularjs将不会运行与范围属性关联的监视,因此UI和其他更新已完成有角度的手表不会发生。
一种可能的解决方案是调用Scope.$apply(),这将有助于执行角度生命周期方法。
var str;
$(document).ready(function () {
str = '{"id":"1","name":"Nang Thang Hai","university":"Hutech University","gender":"true"},{"id":"2","name":"Gio Thang Chin","university":"Foreign Trade University","gender":"false"}';
angular.element('#angularController').controller().doSomthing(str);
angular.element('#angularController').scope().$apply();
//angular.element('#angularController').controller()
});
演示:Fiddle
答案 1 :(得分:0)
$scope.students = JSON.parse(str);
这应该是这样的。不要将jQuery与AngularJS混淆。事实上,你应该尝试使用最少量的jquery与AngularJS
答案 2 :(得分:0)
$.noConflict();
并使用jquery代码。这可能是您的代码工作的一个选项。希望帮助
答案 3 :(得分:0)
如果您正在学习AngularJS,请不要尝试将其与jquery混合使用。没有jquery的简单解决方案
var app = angular.module('app', []);
app.controller('firstCtrl', function ($scope) {
var str = '{"id":"1","name":"Nang Thang Hai","university":"Hutech University","gender":"true"},{"id":"2","name":"Gio Thang Chin","university":"Foreign Trade University","gender":"false"}';
$scope.doSomething = function (str) {
json = JSON.parse('[' + str + ']');
$scope.students = json;
};
$scope.doSomething(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="angularController" ng-controller="firstCtrl" ng-app="app">
<table>
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
<th>University</th>
<th>Gender</th>
</tr>
<tr data-ng-repeat="student in students">
<td>{{student.id}}</td>
<td>{{student.name}}</td>
<td>{{student.university}}</td>
<td>{{student.gender}}</td>
</tr>
</tbody>
</table>
</div>
使用JSFiddle:http://jsfiddle.net/dw8o0bho/2/