【问题标题】:Adding/Updating Items in Local Json File || Separating The Controller and Services Files在本地 Json 文件中添加/更新项目 ||分离控制器和服务文件
【发布时间】:2014-06-15 19:16:21
【问题描述】:

我是 Angular 新手,我正在尝试构建一个简单的待办事项列表应用程序。我使用 Ionic 框架并使用 yeoman 服务器对其进行测试。我已经设法加载了一个本地 json 文件,但我进行了搜索,但找不到如何添加项目/更新它。如果您能指导我如何执行此操作,我将不胜感激。

我想做的第二件事是将我的控制器和服务分开。目前所有的服务都在 controllers.js 文件中。 对于有角度经验的人来说,这两项任务都应该很容易,所以我想我会把它留给你们:P

app.js:angular.module('Todo', ['ionic', 'Todo.controllers'])

Playlist.js(午餐应用时获得的第一页):

 <ion-content class="has-header">
    <ion-list>
      <ion-item ng-repeat="playlist in playlists" href="#/app/playlists/{{playlist.id}}">
        {{playlist.title}}
      </ion-item>
    </ion-list>
  </ion-content>

控制器:

.controller('PlaylistsCtrl', function($scope, $http) {

  $http.get('jsonfile.json').success(function(data){
        console.log(data);
        $scope.playlists = data;
  }); 
})

【问题讨论】:

    标签: javascript json angularjs yeoman ionic-framework


    【解决方案1】:

    我会同时回答你的两个问题;

         .controller('PlaylistsCtrl', function($scope , GetPlaylists) {
             $scope.playlist =[];
             $scope.playlist =  GetPlaylists.getPlaylists(scope);
             // below is a function that you can use for example with buttons ng-click="addNewPlayer('Michel Jackson')"
             $scope.addNewPlayer = function(newPlayer){
                $scope.playlist.push(newPlayer)
            }
          })
    
    
          // To seperate your servises(which is a factory here) , cut and paste this factory in a new js file and include that js file in your index.html
         .factory('GetPlaylists',function($http){
           return{
              getPlaylists:function(scope){
                 var promise = $http.get('jsonfile.json');
                     promise.then(function(data){
                        console.log(data);
                       return data 
                    // I dont know about your json file , maybe you should write data.data or data[0] here
                    //Just console.log(data) it , to find the correct answer
              }); 
          }}
         });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      相关资源
      最近更新 更多