Adding Angular to an existing CodeIgniter project - javascript

I am using CodeIgniter on a daily basis as a frontend and backend development framework and I'am using dynamic frontend stuff like reacting forms and Ajax very rarely. But I need to say: I love it because it's most user-friendly and that's the key of good frontend development.
With forms for example I'm going with to good old way by posting to e new file, validating and pushing it to the database or wherever.
I'll like the way of validating it and giving feedback while the user is typing and this is where I came to angular.
First and foremost I like Angular for reacting forms. For the beginning I'll use it with forms only.
How can I combine CodeIgniter's folder structure with angular's folder structure so that I can use first and foremost CI but angular for the form handling.

Angular usually serves the content from AJAX calls, so you should use CodeIgniter as the webservice API framework.
Let's think you're going to implement a simple list:
First, create your Angular project using sample data (by hardcoding values, for example). When you have your product list working.
HTML
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [
"One",
"Two",
"Three",
"Four"
];
});
angular.bootstrap(document, ['myApp']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in items">
{{item}}
</li>
</ul>
</div>
For now, elements are hardcoded. But we need this elements to be dynamic, with CodeIgniter served data.
For that, create a folder named 'api' at the 'www' folder of your server. Then upload all the CodeIgniter source files. If you have done it correctly, you should see the 'Welcome' controller when you access 'http://yourdomain.com/api'.
For this, I recommend to use this CodeIgniter plugin that allows you to easily create a Webservice API Rest. The main objective is to serve a json object when the Angular asks for data. Then Angular will do the rest.
A brief example:
<?php
header("Content-type: application/json");
class List extends CI_Controller
{
function __construct()
{
// Here you can load stuff like models or libraries if you need
$this->load->model("list_model"); // For example
}
/**
* This method receives a parameter so it can
* filter what list wants the client to get
*/
public function list1($list_number)
{
$list = $this->list_model->getList($list_number);
// If list not exists
if ( empty($list) ) {
$this->output->set_status_header(404);
echo json_encode(
"success" => false,
);
return;
} else { // If has returned a list
// CodeIgniter returns an HTTP 200 OK by default
echo json_encode(
"success" => true,
"list" => $list,
);
return;
}
}
}
Now we can take the info by AJAX. The same code above but changed to get the remote data:
var app = angular.module('myApp', []);
app.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {
// Replace link bellow by the API url
// For this example it would be:
// http://yourdomain.com/api/list/list1/1
$http.get("https://codepen.io/anon/pen/VExQdK.js").
success(function(res) {
console.log(res);
if ( res.success == true ) {
$scope.items = res.items;
} else {
$scope.items = [];
}
});
}]);
angular.bootstrap(document, ['myApp']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in items">
{{item.name}}
</li>
</ul>
</div>
This way you can get a completely functional CodeIgniter API working with Angular. I like to organize methods in different controllers so code is structured to be "readable".
To modify or delete data on the server, you can use $http.post and send parameters to tell CodeIgniter which kind of operation has to do. Remember to use session data to protect the ajax calls of modifying/deleting information (for example if a user tries to update other user's info).
This is not a definitive way, but it's mine. I hope it helped you.

Related

How to design routes when dealing with Laravel API instead of returning Laravel views?

So far I've been building Laravel and Django apps that return views or templates from backend. So far so good.
However, I'm now building a Laravel API that gets called from a frontend AMP code.
In the old ways I do this in Laravel:
From web.php
Route::get('/', function () {
return view('welcome');
});
Or I can return the view from the controller.
However, if the Laravel app is an API that returns JSON, how can I design URLs?
Basically, if someone clicks a link on the homepage that should take hime to a user profile, say:
/user/{id}
Where will I decide how this URL looks like and which endpoint to call?
You can use the same route syntax, but instead of returning a view, you return a json response.
Route::get('api/user', function () {
$data = ['status' => 'success', 'data' => 'stuff'];
return response()->json($data);
});
Take a look at the response documentation for all available types of responses.
I finally wrapped my head around this. At least I think so.
in web.php I have a set of Closures with the URLs that I want. These Closures return views with no data. Similar to this:
Route::get('/', function () {
return view('welcome');
});
And then in the view I call the API endpoints as specified in api.php to render the data that I need in the view.
// List activities
Route::get('activities', 'ActivityController#index');
Laravel 5.3 and above provides the seperate route file routes/api.php, where you can write all routes related to your api requests.
for controller just create a seperate folder in controller folder named as 'Api' and create api related controller in that.
and from there you can write function for corresponding routes. and return json as
return response()->json(['data'=>$data]);
Or you can use https://github.com/nWidart/laravel-modules package to create a sepperate api module in laravel.

drop down using ajax and css

I make a list and make it hyperlink using #Ajax.ActinLink so that on click nested list can be opened using Partial View. When I click on the first list option partial view is displayed but when I click on the second list option, partial view is not opened Here is my code:
<ul id="menu">
<h3>Categories</h3>
#foreach (company company in #Model)
{
<li>
#Ajax.ActionLink(company.COMPANY_NAME, "All", new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "yr",
InsertionMode = InsertionMode.Replace
})
<ul class="sub-menu">
<li id="yr"></li>
</ul>
</li>
}
</ul>
here 2016 and 2017 comes from the partial view but it does not display when i click on the BMW
I see that you're using C# razor syntax, I'm going to infer you're using some form of ASP.NET and creating an application in that manner. They're much better ways to make this call than using AJAX. AJAX is outdated and isn't the best implementation to use when you're working with C# razor syntax. I would make the HTTP GET request call to your controller using JS or angularJS. Take a look at this example of loading comments in a web page using an HTTP GET request below.
<script type="text/javascript">
// Http GET Request to load the comments at each page refresh.
var app = angular.module('myArticleViewer', []);
app.controller('myArticleController', function ($scope, $http, $timeout) {
try {
$http({
method: "GET",
url: "/Documentation/Comments/#Model.ArticlesViewModelID"
}).then(function mySucces(response) {
$scope.data = response.data;
});
} catch (e) {
alert("Error: Bad Request");
}
});
</script>
You're going to make the HTTP GET request to a controller action, in the corresponding controller responsible for the page. Then you're going to return a list of hyperlinked URLs as the value for the controller action you're making the HTTP GET request to. Then, using angularJS and ngDirectives, you're going to write HTML code for a dropdown box and iterate through the data returned from the angularJS HTTP GET request call. This will provide you with the result you seek.

Angular JS/ Html queries on Ionic

Im working on a simple todo app tutorial online based on:
http://ionicframework.com/docs/guide/building.html
What if I wanted a database where instead of a fixed list like in the example, there would be a store where users can input their list dynamically, with room for edit and comments on their tasks outstanding?
a paragraph of text
user name noted
timestamp
It would then appear as a todo list that upon clicking, would open up to be editable and able to add more comments to it?
I have followed a couple of tutorials but all of them use fixed data sets.
I did some research and got the below snippets, my understanding of Angular is still weak so am not exactly clear how the codes work.
Something isnt working and Im not sure why. Can anyone explain and help?
Specifically on params and how id comes into play, as well as the convention of url routing, like #/something.html etc.
The tutorial has firebase back end but if you have any better suggestions (like server and back end language), please let me know. Ive seen tutorials using JSON but again, not sure how that works.
For app.js
.state('bucket.list.detail',{
url: '/list/:itemId',
views: {
'bucket-list-detail':{
templateUrl: 'templates/bucket-list-detail.html',
controller: 'DetailController'
}
}
})
For controller.js
.controller('DetailController', function($rootScope, $scope, $stateParams, $window, $firebase){
$scope.item = items.get($stateParams.itemId);
})
For the view file, bucket-list-detail.html
(I just typed in some trash lines to test the code)
<p>{{ item.item }}</p>
<p>
<a class="button button-small icon ion-arrow-left-b"
href="#/bucket/list"> Main List </a>
</p>
First in your question you have items.get in your controller but nowhere did you define items. Since $firebase is probably a factory of some kind you will probably need to either use that or build some service that is getting your data (via firebase or however).
As an example, I've built a sample todo app using .NET (web api) and Ionic that you can see the source code on github. The overall strategy for firebase should be similar.
I have a route like this, very similar to yours. This is for the details view:
.state('tab.tarea-detail', {
url: '/tarea/:tareaId',
views: {
'tab-friends': {
templateUrl: 'templates/_detalle.html',
controller: 'TareaDetailCtrl'
}
}
})
The state param will contain tareaId.
The list view has an ngRepeat with a link containing the id of a todo (tarea in spanish).
<ion-item ng-repeat="tarea in tareas track by $index" type="item-text-wrap" href="#/tab/tarea/{{tarea.Id}}">{{tarea.Nombre}} {{tarea.Desc}}
<ion-delete-button class="ion-minus-circled" ng-click="tareaEliminar(tarea)">
</ion-item>
And my controller which will receive the id and call a service:
.controller('TareaDetailCtrl', function($scope, $stateParams, tareaService) {
//tareaService is just a wrapper for my ajax stuff, you could call firebase here or you could just use firebase
tareaService.obtener($stateParams.tareaId).then(function (data)
{
$scope.tarea = data;
});
})
The service piece is just calling $http. This is a part of the service:
obtener: function (id)
{
var d = $q.defer();
$http.get(url + '/api/tareadata/obtener/' + id).success(function (data)
{
d.resolve(data);
}).error(function (data, error)
{
d.reject();
});
return d.promise;
}

Can $http.put write data to JSON file

I apologize for the newbie question but I am getting conflicting answers to this while searching on the net.
I have created an AngularJS app to read from a JSON file using $http.get and display the data as a form with each form element binded with ng-model. Ideally I would like the user to be able to edit the desired field and click save, then have that data updated in the JSON file. I have been told that to do this you will need a 3rd party server like NodeJS, but I am seeing other examples that show it being done in videos. Can someone tell me if this is possible without the 3rd party server and if so what is the best practice for doing this.
Thank you
$http GET (for resource located on client) will not work with the Chrome browser and will give a CORS error (unless you disable Chrome web security by opening Chrome using run .../chrome.exe" --allow-file-access-from-files -disable-web-security). Firefox gives an error saying the JSON in not well formed even though it is. Browsers don't seem to like it.
HTML5 LocalStorage is your best bet for client storage where you wish to perform CRUD operations and have the data survive past page refresh. A good example of this is the [TodoMVC example]
(https://github.com/tastejs/todomvc/tree/gh-pages/architecture-examples/angularjs)
A very simple example that saves a json file to localstorage and reads the contents of localstorage is shown. The Service contains a getter and a setter method to interact with localstorage.
INDEX.HTML
<body ng-app = "app">
<div ng-controller="MainCtrl">
<form>
<input placeholder="Enter Name.." ng-model="newContact"/>
<button type="submit" class="btn btn-primary btn-lg"
ng-click="addContact(newContact)">Add
</button>
</form>
<div ng-repeat="contact in contacts track by $index">
{{contact.name}}
</div>
</div>
APP.JS
angular.module('app', ['app.services'] )
.controller('MainCtrl', function ($scope, html5LocalStorage) {
//create variable to hold the JSON
var contacts = $scope.contacts = html5LocalStorage.get();
$scope.addContact = function(contact) {
$scope.contacts.push( {"name":contact} ); //Add new value
html5LocalStorage.put($scope.contacts); //save contacts to local storeage
}
});
SERVICES.JS
angular.module('app.services', [] )
.factory('html5LocalStorage', function () {
var STORAGE_ID = 'localStorageWith_nG_KEY'; //the Local storage Key
return {
//Get the localstorage value
get: function ()
{
return JSON.parse(localStorage.getItem(STORAGE_ID) || '[]');
},
//Set the localstorage Value
put: function (values)
{
localStorage.setItem(STORAGE_ID, JSON.stringify(values));
}
};
});
Otherwise you could use Node and Express and store the JSON file on the server. Use file system module 'fs-extra' to interact with the json file.
You would have to create RESTful API routes for the client to interact with the server using $http and perform CRUD operations.
/put
/get
/delete
/post
I would be interested to see these videos of this being done without the server writing to the file. You cant just "post the .json file" and have it replace the old one, unless you configure your server (apache, nginx, tomcat, node) to do so.

Reading and writing to a server-side file in AngularJS

I'm attempting to create a simple guestbook with AngularJS, and read and write the names to a simple file. Trouble is, I can't seem to get my code to even read from the file.
This is my directory structure:
This is index.html:
<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="ISO-8859-1">
<title>GuestBook</title>
<script src="http://code.angularjs.org/angular-1.0.0rc3.min.js"></script>
<script type="text/javascript" src="javascript/user.js"></script>
</head>
<body>
<h1>Welcome!</h1>
<div ng-controller="UserCtrl">
<ul class="unstyled">
<li ng-repeat="user in users">
{{user}}
</li>
</ul>
</div>
</body>
</html>
This is user.js (Based off this question/answer):
function UserCtrl($scope) {
$scope.users = $(function() {
$.get('data/users', function(data) {
var array = data.split(',');
console.log(array);
});
});
}
And this is my users file:
John,Jacob,James
I'm expecting this outcome:
Welcome!
John
Jacob
James
But instead, all I get is:
Welcome!
So my question is, how can I populate $scope.users with the names in the users file?
I know I've got my AngularJS set up correctly because I was able to get the desired result when I hard-coded it:
$scope.users =[John,Jacob,James];
I've also spent a lot of time googling and searching Stack Overflow for how to read and write to a file with JavaScript and/or AngularJS, but:
No one seems to be trying to do exactly what I'm trying to do;The instructions are either confusing or not really applicable to what I'm trying to do.
I'm also not sure where to begin to write code that will persist names to the users file -- but I'll be happy if I can just read the file for now, and ask how to write to it later in a separate question. (But extra gratitude if you do also show me how to write to it.)
Try injecting angular's $http service into your controller first of all. And make sure you add a '/' before your 'data/users' path. (/data/users)
function UserCtrl($scope, $http) {
$scope.users = [];
$http.get('/data/users')
.success(function(data, status, headers, config) {
if (data && status === 200) {
$scope.users = data.split(',');
console.log($scope.users);
}
});
});
}
You can check your console to see what kind of data is being returned. (Network tab)
edit: just realized the $(function ... part didn't make sense.
The problem with your code is in this stub -
$scope.users = $(function() {
$.get('data/users', function(data) {
var array = data.split(',');
console.log(array);
});
});
Here $scope.users is not the array variable. Instead, it is whatever $() returns.
Your anonymous function is passed only as a parameter to $ function.
Rewrite your controller this way -
function UserCtrl($scope, $http) {
$scope.users = [] // Initialize with an empty array
$http.get('data/users').success(function(data, status, headers, config) {
// When the request is successful, add value to $scope.users
$scope.users = data.split(',')
})
}
And now, since you have
<li ng-repeat="user in users">
{{user}}
</li>
in your view, angular will set up a watch on $scope.users variable.
If the value of $scope.users changes anytime in the future, angular will automatically
update the view.
EDIT -
Along with the above edit, you need to make sure all the files are being served via a web server on the same host:port. Browsers limit AJAX access to another domain:port. Here is a quick way to do start a http server -
Go to the project directory using terminal and type in
python -m SimpleHTTPServer for python
or
ruby -run -e httpd -- -p 8000 . for ruby.
Both will start a basic HTTP server at port 8000, serving content from that particular directory. Having done this, your index.html will be at http://localhost:8000/index.html and your data file should be accessibe as http://localhost:8000/data/user.js (your javascript can still use /data/user.js).
It turns out I can't do what I'm trying to do the way I'm trying to do it. JavaScript by itself can't read files on the Server-Side, only on the Client-Side. To read and persist data, JavaScript has to make calls to a "Back-end" or server, written in something like Java, which isn't just a Browser scripting language.
you entered 'users' instead of 'users.txt' as filename.
This works just fine to me:
function UserCtrl($scope, $http) {
$scope.users = []
$http.get('data/users.txt').success(function(data, status, headers, config) {
$scope.users = data.split(',')
})}

Categories