变量中的静态内容到JSON请求(Angular/Ionic)



我有以下代码,具有静态JSON内容(在其当前状态下工作)。现在,我想调用远程JSON服务来获取数据,而不是静态内容。我做了一个假的web服务来返回相同的JSON数据:http://appserver.falconinet.com/events.lasso

这是我现在得到的。我想我接近了……?

angular.module('starter.services', [])
    .factory('Events', function ($http) {
    var events = [];
    return {
        all: function () {
            return $http.get("http://appserver.falconinet.com/events.lasso");
            starter.services.all().then(function successCallback(response) {
                $scope.events = data;
            })
        }
    }
    return {
        all: function () {
            return events;
        },
        remove: function (event) {
            events.splice(events.indexOf(event), 1);
        },
        get: function (eventId) {
            for (var i = 0; i < events.length; i++) {
                if (events[i].id === parseInt(eventId)) {
                    return events[i];
                }
            }
            return null;
        }
    }
})

这是我的控制器:

// events
.controller('EventsCtrl', function ($scope, Events) {
    $scope.events = Events.all();
    console.log($scope.events);
    $scope.remove = function (event) {
        Events.remove(event);
    }
})
.controller('EventDetailCtrl', function ($scope, $stateParams, Events) {
    $scope.event = Events.get($stateParams.eventId);
})

你的工厂是完美的,只是返回事件当你删除,以便看到修改:

appModule.factory('Events', function() {
  // Might use a resource here that returns a JSON array
  // Some fake testing data
  var events = [{
    id: 0,
    title: 'Swing Dance Party',
    subtitle: 'Lets Get Dancing!',
    when: 'Thursday, Feb 19, 2015 (6:30-9PM)',
    picture: 'http://goldsea.com/Text/images/8198.jpg',
    desc: 'Dance, dance, dance and enjoy mixed drinks, wine, or 40 beers on tap. Krista Mccart & Steve Davis will be doing a short 30 minute class for first time beginners at 6:30 and the dance starts at 7:00. The dance and lesson are free!!!'
  }, {
    id: 1,
    title: 'St. Patricks Day Party',
    subtitle: 'with Special Guest The Menders',
    when: 'Saturday, March 14th (9PM)',
    picture: 'img/menders.png',
    desc: 'Based out of Gastonia, NC, The Menders have been blending influences such as the Beatles, Jack White, The Doors, and Ryan Adams into a folk-laced garage rock sound. Since 2011, they've been honing their craft around NC at venues such as Double Door Inn, The Visulite, The Milestone, Tremont Music Hall, and Snug Harbor. With an upcoming debut self-titled album, lyrics dealing with the complexities of life and death, 4 part harmonies, and energetic live performances, The Menders seek to offer their fans and listeners a music experience that is sure to leave a lasting impression.'
  }];
  return {
    all: function() {
      return events;
    },
    remove: function(event) {
      events.splice(events.indexOf(event), 1);
      return events;
    },
    get: function(eventId) {
      for (var i = 0; i < events.length; i++) {
        if (events[i].id === parseInt(eventId)) {
          return events[i];
        }
      }
      return null;
    }
  }
})
现在创建您的控制器:
appModule.controller('EventsCtrl', ['$scope', 'Events', function($scope, Event) {
  var events = Event.all();
  console.log('events', events);
  var first_event = Event.get(0);
  console.log('first_event', first_event);
  $scope.remove = function(event) {
    console.log(Events.remove(event));
  }
}]);

在你的例子中,你需要定义一个控制器,并在其中注入Events工厂。

在«all»方法中:$http.get("http://appserver.falconinet.com/events.lasso");将返回一个promise,因此在控制器中,您需要实现.then()函数,然后您可以在$scope.events数组中分配json响应数据。

像这样:

(function() {
  angular.module("starter.services", [])
  // Controller
  .controller("EventsCtrl", ["$scope", "Events", function($scope, Events) {
      $scope.events = [];
      Events.all().then(function(response) {
        $scope.events = response.data;
      });
      $scope.remove = function(event) {
        $scope.events.splice(event, 1);
      }
    }
  ])
  // Factory service
  .factory("Events", ["$http", function($http) {
      return {
        all: function() {
          return $http.get("http://appserver.falconinet.com/events.lasso");
        }
      }
    }
  ]);
})();
<html data-ng-app="starter.services">
<head>
  <meta charset="utf-8" />
  <title>Demo</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body data-ng-controller="EventsCtrl">
  <div>
    <ul>
      <li data-ng-repeat="event in events">{{event.title}} <a href="#" data-ng-click="remove($index)">Remove</a>
      </li>
    </ul>
  </div>
</body>
</html>

你需要使用angularjs [$http service]1

return {
  all: function() {
    return $http.get("http://appserver.falconinet.com/events.lasso");
  },

[edit]:还要记住$ http请求将被异步调用,所以如果您将此工厂注入到控制器中,则需要在成功时绑定任何变量。例如:

starter.services.all().then(function successCallback(response) {
  $scope.variableName = data;
})

[edit]:作为对您建议的编辑的回应,您错过了应该在何处设置范围变量(在控制器中)和工厂调用的位置之间的一些关键差异。为了演示,我制作了一个您想要完成的工作:http://plnkr.co/edit/IlIPXHMkkw6lo08eZVIk?p=preview

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, Events) {
  Events.all().then(function successCallback(response) {
    $scope.events = response.data;
  });
});
app.factory('Events', function($http) {
  return {
    all: function() {
      return $http.get("http://appserver.falconinet.com/events.lasso");
    }
  }
});

最新更新