I have been searching through various tutorial sites without success.
My goal is to create an Angular app that communicates with my server over REST. I initially used this as a starting point and got it working, but I decided to start from scratch to gain a better understanding of the process. Setting up the REST server was straightforward for me as a PHP developer, but I'm facing some challenges on the Angular side.
To organize my project, I created a simple directory structure using Yeoman:
- root
- ------app (contains all Angular code)
- ------engine (Yii2 framework resides here)
In app/script/app.js
, I have the following setup:
'use strict'; // What does this line do exactly?
var app = angular
.module('gardeshApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/post/index' , {
templateUrl: 'views/post/index.html',
controller : 'PostList'
})
.otherwise({
redirectTo: '/'
});
});
For handling data received from the server, I created a Post model in the following manner:
app.factory('Post' , ['$resource'] , function($resource){
var Post = $resource('http://localhost/testApp/engine/web/post/:id' , {id : '@id'} , {update: {method: 'PUT'}});
angular.extend(Post.prototype , {
save: function (values) {
if (values) {
angular.extend(this, values);
}
if (this.id) {
return this.$update();
}
return this.$save();
}
});
});
Additionally, I created a controller to fetch the data:
app
.controller('PostList', ['$scope', '$http' , '$resource',
function($scope, $http) {
// $http.get('http://localhost/testApp/engine/web/post').success(function(data){
// console.log(data); // this works fine and gets the json ed data
// });
var posts = new Post();
console.log(posts.query());
}]);
I want to achieve dynamic calls instead of manually using $http.get
. However, I'm encountering an error stating that Post is not defined. How can I properly define a Post Object to represent the fetched model?