这不适用于读取和插入数据,我在js文件夹中有data.json
<ion-content>
<div ng-controller="jsonCtrl" ng-repeat="d in data">
<h2>{{d[0].name}}</h2>
<h2>{{d[0].shortname}}</h2>
<h2>{{d[0].reknown}}</h2>
<p>{{d[0].bio}}</p>
<h2>Total Data {{ getTotalData() }}</h2>
<label>Name</label>
<input type="text" ng-model="Name">
<label>Short name</label>
<input type="text" ng-model="Shortname">
<label>Reknown</label>
<input type="text" ng-model="Reknown">
<label>Bio</label>
<input type="text" ng-model="Bio">
<button ng-click="addData()">Add</button>
</div>
</ion-content>
app.js:
angular.module('starter', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default
// (remove this to show the accessory bar above the keyboard for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})
我的控制器看起来像这样:
.controller('jsonCtrl', function($scope, $http) {
$http.get('data.json').success(function(res) {
$scope.data = res;
console.log($scope.data);
});
$scope.addData = function() {
$scope.data.push({
name: $scope.Name,
shortname: $scope.Shortname,
reknown: $scope.Reknown,
bio: $scope.Bio
});
}
$scope.getTotalData = function() {
return $scope.data.length;
}
});
修改:
data.json
的示例:
{ "speakers" : [
{
"name":"Mr Bellingham",
"shortname":"Barot_Bellingham",
"reknown":"Royal Academy of Painting and Sculpture",
"bio":"Barot has just finished his final year at The Royal Academy"
},
// etc...
]}
答案 0 :(得分:1)
编辑:我编辑了答案,因为OP代码中似乎存在更多问题
首先,您不应将ng-repeat
和ng-controller
放在同一元素上。 ng-repeat
具有更高的优先级,因此,会发生的事情是您为ng-repeat
的每次迭代都有一个控制器。
而是将ng-controller
放在父元素上:
<ion-content ng-controller="jsonCtrl">
<div ng-repeat="d in data">
etc ...
</div>
</ion-content>
其次,您的$scope.data
是一个对象数组,因此{{d[0].name}}
似乎不正确 - [0]
需要什么? - d
已经指向每个项目:
<ion-content ng-controller="jsonCtrl">
<div ng-repeat="d in data">
<h2>{{d.name}}</h2>
<h2>{{d.shortname}}</h2>
<h2>{{d.reknown}}</h2>
<p>{{d.bio}}</p>
</div>
</ion-content>
第三,新项目应该在ng-repeat
之外 - 你不打算重复它,对吗?
<ion-content ng-controller="jsonCtrl">
<div ng-repeat="d in data">
<h2>{{d.name}}</h2>
... etc
</div>
<label>Name</label>
<input type="text" ng-model="Name">
<label>Short name</label>
<input type="text" ng-model="newItem.shortname">
... etc
<button ng-click="addData()">Add</button>
</ion-content>
最后,我强烈建议您始终将绑定ng-model
用于某个对象的属性(或者,始终使用点.
) - 而不是直接使用范围属性。这与范围的原型继承有关 - 如果没有点(.
),你将写入子范围的属性,如果某个指令(例如ng-if
)创建了一个。它也更容易重置。
$scope.newItem = {};
$scope.addData = function(){
$scope.data.push($scope.newItem);
$scope.newItem = {};
}
<label>Name</label>
<input type="text" ng-model="newItem.name">
<label>Short name</label>
<input type="text" ng-model="newItem.shortname">
... etc