Using Laravel (or other PHP MVC) and AngularJS - angularjs

I am making an app and I was wondering what is a better way to approach this. I want to use Laravel as the backend, and AngularJS as the frontend.
Should I then leave the entire rendering and View completely to AngularJS and only use Laravel through AJAX calls? Or should I still load the basics from Laravel, and use AngularJS to enhance the experience?

Yes. You could use Laravel as RESTFul API and consume from client without using blade (so if you want it)
Here example:
class PostController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
return Post::orderBy('created_at', 'desc');
}
}
service in angular: ( I use Restangular lib, but you can use $http)
app.factory("PostsService", function(Restangular) {
return {
/*
* GET /posts -> Trae todos los posts
*/
all: function() {
return Restangular.all('posts').getList();
}
}
});
controller angular:
app.controller('HomeController', function($scope, PostsService){
PostsService.all().then(function(posts){
$scope.posts = posts.data;
});
});

Related

How to pass data between angular controllers through mvc controller

I have an angularjs controller which i wanted to pass data to other angularjs controller, and here i am not using angularjs routing, only using MVC routing,
As i am using MVC Routing, i had passed data from angularjs controller to MVC controller action method, and from there i have to return to another angularjs controller, i am unable to pass data to the other controller or even it is not returning to the MVC routed View(), and in angularjs controller i used $window.location.href to rediect to the expected view, But unablt to pass data
AngularJS Controller
$http.post(attserviceBasePath + '/Dashboard/PostMembers', group)
.then(
function (response) {
window.location.href = attserviceBasePath + '/Attendance/Dashboard/GroupedTeamMembers';
}, function (error) {
//console.log(error);
});
MVC Controller:
[HttpPost]
public ActionResult PostMembers(GroupedMembers grpMembers)
{
var result = grpMembers;
return RedirectToAction("GroupedTeamMembers", result);
}
public ActionResult GroupedTeamMembers(GroupedMembers grouped)
{
return View(grouped);
}
it is not working ...
please help me to pass data from one angularjs controller to another angularjs controller through MVC controller...
Thanks In Advance.......
You have to use sessions to pass data between controllers. check this one ex

Angular js retreiving and displaying data from backend to front end

I am working on app where I have 2 subdirectories inside public namely admin and core. admin is for admin users where we need to login and add,Edit,delete posts while in core we have pages which a public user or visitors can see. Now what I want is that I have a CRUD functionality implement in admin. I have controller, routes and services. but what I don't know is that how can I display the data in core views for public users I needs steps to to re-use some of the code from admin and retrieve and display data in core views.
Here is a link to the directory structure: http://take.ms/LdaWk
Imagine the following structure...
app
|- admin
|- api
|- core
The api defines your CRUD functions. For example, in Slim PHP something like
$api = new \Slim\Slim();
// audio/video
$api->get('/av', 'getAVs');
$api->get('/av/:id', 'getAV');
$api->post('/add/av', 'addAV');
$api->put('/update/av/:id', 'updateAV');
$api->delete('/delete/av/:id', 'deleteAV');
// define functions that handle http requests above...
Now in admin, you can call the api in angularjs using $http. For example calling the resource POST /add/av
var admin = angular.module('adminApp', ['ngRoute']);
admin.controller('addAvCtrl', function($scope, $http, MsgService){
MsgService.set('');
// process the form
$scope.submit = function() {
$http.post('../api/add/av', $scope.formData)
.success(function() {
MsgService.set('Success!');
});
};
$scope.message = MsgService.get();
});
In core you can use the same api to display data. For example calling the resource GET /av/:id
var core= angular.module('coreApp', ['ngRoute']);
core.controller('mediaCtrl', function($scope, $http, $routeParams){
$http.get('../api/av/' + $routeParams.id)
.success(function(response) {
$scope.media_detail = response;
});
});
Obviously, this is a rough outline. You would need to fill out the code, but it displays the principle.
You can implement a component base structure, something like:
Components
TestComponent
AddTestComoonent
EditTestComponent
ListTestComponent
That each component has own module and router. and whenever you want you can just inject the module and use it

Waiting until $resource finished to load in my controller before continuing

I'm building a rest api with fosrestbundle and I manage the frontend with angular and Twig template. One on my url address looks like this :
http://mywebsite/myroute/idContain
When I load the url in my browser, in a twig template (kind of html), I retrieve the parameter "idContain" (comming from a fosrestbundle controller) with ng-init of angularjs like this :
<div class="container-fluid" ng-init="getContainByID({{ idContain }})">
//...lot html div with angularjs directives
</div>
And immediately, ng-init will go to my angularJS app finds getContainByID(idContain) to run it.
This one looks like this :
angular.module("myApp", ["ngSanitize", 'angular.filter', 'ui.tinymce', ...])
.config(function($interpolateProvider, ...) {
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
})
.controller("myCtrl",function ($filter,..., myService)
{
// lot of code...
$scope.getContainByID = function(idContain)
{
$scope.currentContain = myService.getContains(idContain);
$scope.containRoot = $scope.currentContain.contain.containRoot;
...
}
// lot of code...
}
The fact is that, myService.getContains(idContain) come from my rest service looking like this :
angular.module("MyServiceRest", ['ngResource'])
.factory("myService", function ($rootScope, $resource) {
var apiData = $resource(
"/api", {},
{
...
"getContains": {method: 'GET', isArray: false, url: "mywebsite/api/myroute/:containid"}
...
});
return {
getContains: function (idContain) {
return apiData.getContains({containid: idContain});
}
}
});
Now the problem is, when I run my angularjs App, $scope.containRoot doesn't wait until myService.getContains(idContain) (coming from my asynchroeous $resource service) finished to load, and caused errors making my webapp crash.
How can I do, to force $scope.containRoot and the rest of my angular code to waiting until myService.getContains(idContain) (connected to the api resource) completly finished to load before continuing ?
$resource makes an asynchronous request but immediately reurns an empty object or array.
There are numerous ways you could handle your issue.
One would be not to worry about declaring $scope.containRoot and just using currentContain.contain.containRoot in the view. This property will get rendered after the request is received
Another is to use the $promise that is also returned by $resource and assign the scope property in promise callback
$scope.currentContain = myService.getContains(idContain);
$scope.currentContain.$promise.then(function(){
$scope.containRoot = $scope.currentContain.contain.containRoot;
});
Another is to use a routing resolve based on the same promise so the route( or state depending on router) is noot entered until the request is complete

How to communicate using iframe between 2 angular apps ?

I have two different angular apps. I have to open a view of 'app_2' using iframe in 'app_1'. I also need to post some data from 'app_1' to 'app_2'.
How to achieve this in angularJS?
Thanks in advance. #SOS
I would use consider using postMessage...
In Angular terms this would mean that one app would send messages and the other one would be listening to messages.
So on the App that sits within the iframe you can make a factory that does the following:
/**
* App that sits within iframe:
*
* Inject this factory into your controller and call
* iFrame.messageParentIframe({hello: 'world'}) to send messages
* to the parent iFrame
*/
angular
.module('app')
.factory('iFrameMessenger', function($window) {
return {
messageParentIframe: function(message) {
$window.parent.postMessage(message, '*');
}
};
});
On the parent iFrame your code should look something like this:
/**
* App that is on parent iframe:
*
* Just using a controller for the sake of simplicity,
* but you could also use a Factory that only receives
* messages from iFrames and handle them according to each
* action, etc. You can get creative here on how you want
* to handle it.
*/
angular
.module('app')
.controller('AppCtrl', function($window) {
$window.addEventListener('message', function() {
// handle messages received from iframe
});
});

How to retrieve constants for AngularJS from backend

i have some application settings that i want to retrieve from backend, so that they would be available to all of my application controllers via injection. What is the most angular-way to do that?
1) If i only needed settings for one or few controllers i could retrieve them via routing resolve method, but what about global application scope?
2) I could use the .run() method, but since call will be async i have no guaranties that my config will be loaded before i access controllers.
Currently my settings are returned as a json object, and my templates/html files are simply served by web server. So i cannot embed anything into script tags, parse html on the server side or any similar technique.
I would create a service for your settings. Then using the .run() method, called a service that returns your app settings data:
angular
.module('YourApp',[])
.service('Settings',function(){
this.data = {}
})
.run(function(Settings,$http){
$http
.get('/ajax/app/settings')
.success(function(data){
Settings.data = data
})
})
function Controller($scope,Settings){
// use your Settings.data
}
http://docs.angularjs.org/api/angular.Module#methods_run
There is a neat plugin to do the job. https://github.com/philippd/angular-deferred-bootstrap
You need to change bootstrap method
deferredBootstrapper.bootstrap({
element: document.body,
module: 'MyApp',
resolve: {
APP_CONFIG: function ($http) {
return $http.get('/api/demo-config');
}
}
});
angular.module('MyApp', [])
.config(function (APP_CONFIG) {
console.log(APP_CONFIG);
});

Resources