AngularJS Codeigniter base_url path settings - angularjs

I am creating a website with Codeigniter 3 and AngularJs. While delevolping i have faced some issues with base url in codeigniter. Im attaching an image file of my directory struture.
In my mainpage(views/home.php) i put a ng-view for loading different pages. Here i am using angularjs ngRoute for routing.
Here is my code.
var myApp = angular.module("myApp",["ui.bootstrap","ui.router","ngRoute"]);
myApp.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "application/pages/mainpage.php"
})
.when("/about", {
templateUrl : "application/pages/about.html"
})
.when("/services", {
templateUrl : "application/pages/services.html"
})
.otherwise("/",{
templateUrl: "application/pages/mainpage.php"
});
});
Inside that mainpage.php i am listing some profile contents(dummy contents) which is residing inside a json file(datas/data.json). And all the content were listing. And inside this listing i placed a button with ng-click="myName"
Here is the code:
<div class="container" ng-controller="ListController">
<div class="row">
<div class="col-lg-12 text-center">
<h1>Starter Template</h1>
<p class="lead">Complete with pre-defined file paths that you won't have to change</p>
<div class="row">
<div class="col-sm-6 col-md-4 wow zoomIn" data-wow-delay="0.5s" ng-repeat="items in artists">
<div class="thumbnail">
<img ng-src="{{settings.base_url}}/application/assets/images/profile/{{items.shortname}}.jpg" alt="...">
<div class="caption">
<h3>{{items.name}}</h3>
<p>{{items.bio}}</p>
<p>Button Button</p>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.row -->
</div>
All my js code were wriiten in app.js(assets/js/app.js) including Angular Js. In this js file i have setup a base_url variable same as in codeigniter config.php file
$config['base_url'] = 'http://localhost/AngularExPack/Angular_Bootstrap_CI_1/';
inside app.js
var base_url= 'http://localhost/AngularExPack/Angular_Bootstrap_CI_1/'
When i click on my button with ng-click="myName" i want to get a controller(Codeigniter controller) and want to execute a function inside that controller. Here iam using auth.php(controllers/auth.php) and function name as functionOne();
public function functionOne()
{
/*$this->load->view('home1');*/
echo "hai";
}
For that iam using $hhtp.post and var base_url for path. But i didnt get that output and it is not passing to that controller.
myApp.controller('ListController', ['$scope', '$http', 'settings', function($scope, $http) {
$http.get('application/datas/data.json').success(function(data) {
$scope.artists = data;
});
$scope.myName = function() {
alert("hai1");
/**/
$http.post(base_url + 'auth/functionOne').success(function(response) {
$scope.data = response
console.log($scope.data);
alert($scope.data);
});
}
}]);
ng-click="myName" function works fine. But it is not passing to the function functionOne inside that controller auth.php. I think the issue is probably with the base_url path. If any one knows this plz help me to solve this issue.

Well, I don't know it this will help you, but this is how I am doing it:
I have this function in a service:
saveFunction: function(obj, user, securityToken){
return $http({
method: 'POST',
url: 'index.php/controller/saveFUnction',
data: $.param({
postID: obj.id ,
csrfTokenName: securityToken,
postName: obj.name,
.....
userID: user.id
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
if your csrfToken is active in codeigniter config, you need to pass it in your form, as hidden type field. Also, you must set the content type in the headers.

Related

making a url with the $http using routing params error

Below is the link of my file. I was unable to generate a url from the existing url generated from $http, by using $parent.$index and $index as ids from routing, please help: Plunker
I have applied the same kind of functionality to another application it worked have a look at this Plunker
Inside the loadSingleMatch() function error in updating the url inside the $http
error image:-
Code
app.controller("selfController", ['$http', '$routeParams',
function($http, $routeParams) {
//create a context
var main = this;
this.parentId = $routeParams.parent;
this.childId = $routeParams.child;
console.log(this.parentId);
console.log(this.childId);
this.urlOne = "https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.json";
this.urlTwo = "https://raw.githubusercontent.com/openfootball/football.json/master/2016-17/en.1.json";
this.loadSingleMatch = function() {
$http({
method: 'GET',
url: main.urlOne + '/' + main.parentId + '/' + main.childId
}).then(function successCallback(response) {
main.matchData = response.data.rounds[main.parentId].matches[main.childId];
console.log(main.matchData);
}, function errorCallback(response) {
console.log(response);
});
}
}
]);
The a tag should be inside the second ng-repeat:
<div class="w3-row w3-hover-shadow w3-hover-border-black w3-border w3-white w3-padding-16" ng-repeat="x in matchDay.matches">
<a ng-href="#/indiTeam/{{$parent.$index}}/{{$index}}" >
<div class="w3-small">
<div class="w3-col s6 ">
{{x.team1.code}} vs {{x.team2.code}}
</div>
<div class="w3-col s6">
<div class="w3-padding-small">
{{ x.date | date: 'shortDate'}}
({{$parent.$index}} {{$index}})
</div>
</div>
</div>
</div>
</a>
</div>
See modified plunker:
https://plnkr.co/edit/PeqUHIZVC0HsqdjLkdOo?p=preview
Finally found out the answer to my question
the url inside the $http should not be changed only the response inside of it needs to be changed
the url: main.urlOne is the change that bought the output as expected

it just keep loading the same page with angular ngRoute?

I am learning angular by building a simple bookstore web app using nodejs as a restful api server. I built the server and it works fine, but once it comes to the front end I face an issue. I built the main page using angular ngRoute to get the data from the server and presented as following:
the picture and the title and the description angular read it with no problem but once I press the button "View Details" I should be redirected to a details page using the book id from the server.
From the front End the route provider:
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider){
$routeProvider.when('/',{
controller: 'BooksController',
templateUrl: 'views/books.html'
})
.when('/books',{
controller: 'BooksController',
templateUrl: 'views/books.hrml'
})
.when('/books/details/:id',{
controller: 'BooksController',
templateUrl: 'views/book_details.html'
})
.when('/books/add', {
controller: 'BooksController',
templateUrl: 'views/add_book.html'
})
.when('/books/edit/:id', {
controller: 'BooksController',
templateUrl: 'views/edit_book.html'
})
.otherwise({
redirectTo: '/'
})
});
Books Controller:
var myApp = angular.module('myApp');
myApp.controller('BooksController', ['$scope', '$http', '$location',
'$routeParams', function($scope, $http, $location, $routeParams){
console.log('BooksController loaded...');
$scope.getBooks = function(){
$http.get('/api/books').then(function(response){
$scope.books = response.data;
});
}
$scope.getBook = function(){
var id = $routeParams.id;
$http.get('/api/books/'+id).then(function(response){
$scope.book = response.data;
});
}
}]);
books html where the panel being designed:
<div class="panel panel-default" ng-init="getBooks()">
<div class="panel-heading">
<h3 class="panel-title">Latest Books</h3>
</div>
<div class="panel-body">
<div class="row">
<div ng-repeat="book in books">
<div class="col-md-6">
<div class="col-md-6">
<h4>{{book.title}}</h4>
<p>{{book.description}}</p>
<a class="btn btn-primary"
href="#/books/details/{{book._id}}">View Details</a>
</div>
<div class="col-md-6">
<img class="thumbnail" src="{{book.image_url}}">
</div>
</div>
</div>
</div>
</div>
</div>
This the details book html where by clicking the button it must be redirected to:
details_book.html
<div class="panel panel-default" ng-init="getBook()">
<div class="panel-heading">
<h3 class="panel-title">{{book.title}}</h3>
</div>
<div class="panel-body">
<div class "row">
<div class ="col-md-4">
<img src="{{book.image_url}}">
</div>
<div class ="col-md-8">
<p>{{book.description}}</p>
<ul class="list-group">
<li class="list-group-item">Genre: {{book.genre}}</li>
<li class="list-group-item">Author: {{book.author}}</li>
<li class="list-group-item">Publisher: {{book.publisher}}
</li>
</ul>
</div>
</div>
</div>
</div>
and this is the get request from the server to prove the server working find using a certain id
The error I get once I open the main page:
And this error I get once I press the button:
Note: Once I press the button it give me this url:
http://localhost:3000/#!/#%2Fbooks%2Fdetails%2F599701c1f3da51117535b9ab
where the id is 599701c1f3da51117535b9ab which we can see it in the end of the url. But it should give url exactly such as:
http://localhost:3000/#!/books/details/599701c1f3da51117535b9ab
and once I write this url manually I get to the page which is the details with no problem but once I press the button from the book.html page I get the previews strange url again which is:
http://localhost:3000/#!/#%2Fbooks%2Fdetails%2F599701c1f3da51117535b9ab
Which load no where.
This is the github url for all the documents:
https://github.com/AbdallahRizk/BookStore.git
Any suggestions Please!!
use $rootScope instead of $scope for getBook function
$rootScope.getBook = function(){
var id = $routeParams.id;
$http.get('/api/books/'+id).then(function(response){
$scope.book = response.data;
});
init(getBook);
}
Note: add $rootScope to your BookController
Seems like I have hashprefix !, then my URL should also have ! after hash(#)
href="#!/books/details/{{book._id}}"
Since Angular 1.6 hashprefix is defaulted to !, you can disable this behavior by setting hashPrefix to ''(blank).
.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('');
}
]);
Note: This answer from, #Pankaj Parkar at I get a weird templateURL not as it suppose to give with angular?

ui-router Main View is rendering thrice and no controller are registering

I am trying to create a SPA using angular ui-router with MVC. I am facing three issues.
1.The controllers OfferController.js and OfferCustomizationController.js are not registering.
2.I am getting the errors ' No reference point given for path '.offer', No reference point given for path '.customizations'.
3. Main view is rendering thrice.
I have no clue what am i missing. Please help.
I have included the following files in my Layout.cshtml:
<script src="#Links.Scripts.angular_min_js"></script>
<script src="#Links.Scripts.ProductCatalog.app_js"></script>
<script src="#Links.Scripts.ProductCatalog.service_js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-animate.min.js"></script>
I have made two views. Offers And OfferCustomizations. And a main view. Following is my code for the main view:
<div class="inside-data-div" ng-app="ProductCatalog">
#*<div ui-view></div>*#
<div class="col-lg-12">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div id="form-container">
<div class="page-header text-center">
<h2>Create Offer</h2>
<!-- the links to our nested states using relative paths -->
<!-- add the active class if the state matches our ui-sref -->
<div id="status-buttons" class="text-center">
<a ui-sref-active="active" ui-sref=".offer"><span>1</span> Offer Details</a>
<a ui-sref-active="active" ui-sref=".customizations"><span>2</span> Offer Customizations</a>
</div>
</div>
<!-- use ng-submit to catch the form submission and use our Angular function -->
<form id="signup-form" ng-submit="SaveForm()">
<!-- our nested state views will be injected here -->
<div id="form-views" ui-view></div>
</form>
</div>
<!-- show our formData as it is being typed -->
<pre>
{{ formData }}
</pre>
</div>
</div>
</div>
</div>
Following is my code of app js:
var productCatalogApp = angular.module('ProductCatalog', ['ui.router']);
productCatalogApp.value('appName', 'Product Catalog');
productCatalogApp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
// route to show our basic form (/form)
.state('wizard', {
url: '/wizard',
templateUrl: 'WizardSubForm',
controller: 'WizardMainController'
})
// nested states
// each of these sections will have their own view
// url will be nested (/form/profile)
.state('wizard.offer', {
url: '/offer',
templateUrl: 'OfferForm',
controller: 'OfferCtrlr'
})
// url will be /form/interests
.state('wizard.customizations', {
url: '/customizations',
templateUrl: 'OfferCustomizations',
controller: 'CustomizationCtrlr'
});
// catch all route
// send users to the form page
$urlRouterProvider.otherwise('/wizard/offer');
});
productCatalogApp.controller('WizardMainController', function ($scope) {
// we will store all of our form data in this object
$scope.formData = {};
// function to process the form
$scope.SaveForm = function () {
alert('awesome!');
$scope.formData = { "Offer": $scope.offer, QuestionGroups: $scope.QuestionGroups }
};
});
This is how i'm registering my controllers. Below is the one for offercontroller.
var app = angular.module('ProductCatalog.controllers', []);
app.controller('OfferCtrlr', function ($scope, $http, $modal) {
});
Any help will be appreciated.

iam trying to send data from angular services to nodejs backend Nothing happens

I have enclosed my service function here. Iam trying to send a simple data to node backend but nothing happens. But at this API Endpoint the things works well its saving data in good shape(in postman). Iam sure iam wrong somewhere here in angular No Errors are triggering. No http request is raised.
App.service('UserServices', function($rootScope, $http) {
this.AddToInviteList = function(email, cb) {
var url = $rootScope.api_server_url + "/users/addtoinvitelist";
$http({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} // set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
}
})
and my controller code is here,
App.controller('InviteController', function($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.AddToInviteList = function(email) {
UserServices.AddToInviteList(email, function(dataresponse) {
console.log(dataresponse);
})
}
});
And my HTML View div is below.
<div class="tab-content">
<!--NEWSLETTER FORM-->
<div class="panel panel-minimalize">
<h2 class="signin-brand animated-hue"> <i class="fa fa-rocket"></i> MEDICOSHERE</h2>
<div class="panel-body bg-inverse ui-corner-all">
<form action="#">
<div class="form-group">
<label for="subcribeNewsletter" class="control-label">INVITE FORM<br> <small>We are happy to invite you to medicoshere, So please enter your email ID in the below form.</small></label>
<div class="input-group input-group-in input-group-sm">
<div class="input-group-addon"><i class="fa fa-envelope text-belpet"></i></div>
<input class="form-control" id="subcribeNewsletter" placeholder="johndoe#mail.com" ng-model="email" required>
<div class="input-group-btn">
<button type="submit" class="btn btn-default text-belpet" ng-click="AddToInviteList(email)"><strong>OK</strong></button>
</div>
</div>
</div><!-- /.form-group -->
</form><!-- /form -->
</div><!-- /.panel-body -->
</div><!-- /.panel -->
<!--/END NEWSLETTER FORM-->
</div><!-- /.cols -->
</main>
Will it would be nice to have a bit more of information regarding your problem but I already see some potential issues.
First of all I hope that App variable (App.service) is an instance of your angular's main module.
Also, I believe you must return the function in an object at the begging or end of your service declaration. That way it'll work as expected when calling it from your controller.
So I believe it should look something like this:
var App = angular.module('myApp');
App.service('UserServices', function($rootScope, $http) {
this.AddToInviteList = function(email, cb) {
var url = $rootScope.api_server_url + "/users/addtoinvitelist";
$http({
method: 'POST',
url: url,
headers: { 'Content-Type': 'application/x-www-form-urlencoded '
}
// set the headers so angular passing info as form data (not request payload) })
.success(function(data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
}
return {
AddToInviteList:AddToInviteList
}
})
Sorry for the bad indentation :) writing from a smartphone.
Hope it helps!
EDIT
Also, are you sure you added the file to your index.html? :D
Another thing to check
You might want to check in your routing is OK. Perhaps you're not associating that view to the right controller. That or not including the service file could be one of the reasons you're not getting any errors.

Angular ng-bind disappearing using escaped fragments with Mean-SEO

I have an angular web app that I am trying to get escaped_fragments to work using Mean-seo (under the covers it uses phantomjs headless browser)
I am getting strange behaviour I can't explain.
The non escaped fragment works fine.
With escaped fragments some of the content immediately disappears.
I have an object that I am reading from the mongo db in the resolve section of the routes config like so.
state('view-creator-test', {
url: '/view-creator-test/:creatorId',
templateUrl: 'modules/creators/views/view-creator-test.client.view.html',
resolve: {
creator: function($stateParams, Creators) {
return Creators.get({
creatorId: $stateParams.creatorId
}).$promise;
}
},
controller: function($scope, creator) {
$scope.resolveCreator = creator;
}
}).
then the view template is
<section data-ng-controller="CreatorTestController" >
<!-- !CREATOR PROFILE -->
<section class="profile-header inverse">
<div class="container">
<!-- AVATAR -->
<div class="row">
<!-- NAME / LOCATION -->
<div class="col-sm-8 col-sm-offset-1 col-xs-12 text-center-sm">
<div class="row">
<div class="col-sm-6 col-xs-12">
<h2 class="name">{{creator.name}}</h2>
<h2 class="name" ng-bind="creator.name"></h2>
</div>
<h2 class="name">{{test}}</h2>
<h2 class="name" ng-bind="test"></h2>
</div>
</div>
</div>
</div>
</section>
</section>
then the controller is
'use strict';
angular.module('creators').controller('CreatorTestController', ['$scope',
function($scope) {
$scope.test = 'Leo was Here';
$scope.creator = $scope.resolveCreator;
}]);
the result is that the creator name is filled in for {{creator.name}} but is not filled in for ng-bind="creator.name".
'Leo was here' is filled in for both.
Thanks
Instead of defining controller function in state and then do assign that $scope inside variable through template, you could place the CreatorTestController inside the route, so that you directly inject the dependency inside the CreatorTestController function, Remove ng-controller from the template
.state('view-creator-test', {
url: '/view-creator-test/:creatorId',
templateUrl: 'modules/creators/views/view-creator-test.client.view.html',
resolve: {
creator: function($stateParams, Creators) {
return Creators.get({
creatorId: $stateParams.creatorId
}).$promise;
}
},
controller: 'CreatorTestController'
})
Controller
'use strict';
angular.module('creators').controller('CreatorTestController', ['$scope', 'creator', //<-- injected resolve method here.
function($scope, creator) {
$scope.test = 'Leo was Here';
$scope.creator = creator;
}]);

Resources