How to remove QueryString in Angular JS - javascript

I have an URL http://sitename.com/#/products/manage-options/31?form_id=32&type=create-template
Here above my URL I want to remove type but below my code not working properly. Please Check
My Current page URL - http://sitename.com/#/products/manage-options/31?type=create-template
Click Here
$scope.clickMe = function(){
$location.search('type', null);
$state.go('products.manage_options', ({form_id: $stateParams.form_id}));
};
After page redirecting I saw type QueryString not removed.
My output is - http://sitename.com/#/products/manage-options/31?form_id=32&type=create-template I want http://sitename.com/#/products/manage-options/31?form_id=32
please help me.
EDIT:
Router
.state('products.manage_options', {
url: '/manage-options/:product_id?form_id=&type',
templateUrl: "views/product/manage_options.html",
controller: "manageAttributeCtrl",
data: {pageTitle: 'Manage Options'},
})

Remove
$location.search('type', null);
Change following line :
$state.go('products.manage_options', ({form_id: $stateParams.form_id, type:null}));

see documentation https://docs.angularjs.org/api/ng/service/$location#search
$state.go('products.manage_options', ({form_id: $stateParams.form_id, type:null}));

Related

pass AngularJS value / variable inside javascript

Here is my Angular data (i write here only one data entry as demo, actually i have so many entry):
var font = angular.module('font', []);
font.controller('fontListCtrl', function($scope) {
$scope.font = [
{
id: "_001",
name: "Kalpurush",
download: "1"
}
]
var download = scope.font.download
});
I want to pass my download ID into inside javascript inside html. but i cannot success.
<div class="fontbox" ng-repeat="font in font">
{{font.name}}
<script>ccount_display('download')</script>
</div>
Please help me, thank you :)
I am making some assumption based on your code/question. If that's not the case, I can modify my solution.
There are couple of issues in your code. I've tried to fix them below:
var font = angular.module('font', []);
font.controller('fontListCtrl', function($scope) {
$scope.fonts = [{
id: "_001",
name: "Kalpurush",
download: "1"
}];
//assuming you're accessing above scope variable, your code had 'scope' but not $scope. And it's an array.
$scope.download = $scope.fonts[0].download;
//assuming you want to use download variable in your HTML.
});
Also the HTML is incorrect. You should do something like below:
ng-repeat="font in fonts"
If i understand the problem correctly you want to pass id into the count_display method you can do that by passing font.id and the use of the <script> tag in this context is not necessary. Hope this helps.

href is not automatically generated when ui-sref is used

I'm trying to use angular js ui router to route my page.
Here's the code that I've written:
<a ui-sref="transporterEditDetails({companyId: '{{d.companyId}}' )" style="cursor: pointer">{{d.companyName}}</a>
Here's the js code :
var routerApp = angular.module('routerApp', ['ui.router','ui.bootstrap','xeditable','google.places','angular-loading-bar','ui.select','angularUtils.directives.dirPagination','notificationsTruckway','ui.tinymce'])
routerApp.config(function($stateProvider, $urlRouterProvider,cfpLoadingBarProvider) {
$stateProvider
.state('transporterEditDetails', {
url: '/transporterEditDetails/:companyId',
controller:'TransporterEditDetailsController',
templateUrl: 'Transporter-editDetails.html'
})
routerApp.controller('TransporterEditDetailsController', function($scope,$location,$http,usersFactory,$stateParams) {
$scope.companyId = $stateParams.companyId;
}
I don't know what's wrong in my code, I'm unable to get the href attribute which should be generated automatically.
Did you try without quotes and parentheses
<a ui-sref="transporterEditDetails({companyId: d.companyId})" style="cursor: pointer">{{d.companyName}}</a>
You don't need to use {{}}(interpolation) inside ui-sref. Also remove '(wrapped single quote)
ui-sref="transporterEditDetails({companyId: d.companyId })"

RESTLET - Angular.JS File Upload on Client Side

We are using Restlet for our API on the client side, everything server side is written in Laravel 5. We are having trouble in one portion. We have a couple endpoints that require you to upload a file. In Angular, I have only gotten that to work using the following method thus far:
var fd = new FormData();
fd.append('image', $scope.file);
$http.post(apiURL + "/upload", fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}).then(function(response) {
//yay it worked
}, function(response) {
//try again
});
I don't know why that is the only way I have been successful, but I would like to change it over to the Restlet endpoint I have created. For most of my calls, it is as simple as this:
$rootScope.restlet.getCompanyAll().then(function(response) {
$scope.companies = response.data;
});
and
var config = {
params: {
start: "2016-01-01",
end: "2016-01-31"
}
};
var id = 1;
$rootScope.restlet.getCompanyStatsCompany_id(id, config).then(function(response) {
$scope.companies = response.data;
});
Pretty simple, but when I try to implement the post of an image, it doesn't recognize it, and leaves the image out completely. Here is the code I am attempting to use, it works with the non-Restlet way, but doesn't work with Restlet.
var config = {
params: {
name: $scope.newCompany.name,
rep_id: $scope.newCompany.rep_id,
image: $scope.image_input
}
};
var id = 1;
$rootScope.restlet.postCompanyCreate(config).then(function(response) {
$scope.companies = response.data;
});
Has anyone gotten something like this to work? And if so, how does it work? Thanks! :)
EDIT 1:
Here is the HTML of the page I have set up. It does have a file input, but for some reason it Restlet doesn't like the file. I have tried a plain file input, along with an input with a directive on it. The current version I am using is an image, that when clicked is linked to an file input that is hidden. I am also using a custom directive on it currently.
HTML:
<div class="modal-body">
<form ng-submit="createCompany()">
<!-- OTHER FORM STUFF GOES HERE -->
<div class="col-sm-12">
<img src="" id="imagePreview" onClick="$('#imageUpload').trigger('click');" style="max-width: 100%;" />
<input type="file" style="display: none;" id="imageUpload" file="file" />
</div>
<!-- FORM SUBMIT AND RESET BUTTONS HERE -->
</form>
</div>
Custom Directive:
app.directive('file', function() {
return {
scope: {
file: '='
},
link: function(scope, el, attrs) {
el.bind('change', function(event) {
var file = event.target.files[0];
scope.file = file ? file : undefined;
scope.$apply();
});
}
};
});
You didn't post your HTML but I assume that you are using an input with a type of file to specify the file to upload and binding to it with ng-model or some native Angular binding mechanism. I have no idea why, but Angular doesn't support this. There are 2 common ways to implement this.
The 1st is to use a directive that works around this issue. There's one here: https://github.com/danialfarid/ng-file-upload.
The 2nd, and at least where I would start, is you can simply use document.getElementById to retrieve the file name from the input in your controller. IOW, $scope.file = document.getElementById("myFileThingy").value.

Angular ng-repeat scope issue

Nothing in my {{}} are showing in my html file. Can someone please tell me what I am doing wrong. I have no errors in my console.
"GOT DATA" will print in my console, but not show in my file.
The is my html code
<div class="announcements" ng-controller="onBusinessAnnouncementCtrl as announcements">
{{announcements.latest}}
</div>
This is my js code pulling from the server
app.controller('onBusinessAnnouncementCtrl', function($scope, $http) {
$http.get('http://localhost:3000/latest')
.success(function(responses) {
//$scope.latest = responses;
$scope.latest = "GOT DATA";
console.log($scope.latest);
});
});
Because you use the controller as syntac you should apply the variables in your controller to this instead of $scope.
See the same problem in AngularJS Ng-repeat is not working as expected where a repeater was used
below the answer on the previous question:
In your repeater you're looping over announcements.announcements in your controller you set $scope.announcements = response.
Either you change the repeater in ng-repeat="eachAnnouncement in announcements" or change your scope variable to: $scope.announcements = {announcements : response}
Figured it out! For reference:
There is nothing showing in my HTML because there is no value assigned to the controller. To assign "latest" to my controller I have to do this:
app.controller('onBusinessAnnouncementCtrl', function($scope, $http) {
$http.get('http://localhost:3000/latest')
var this = this;
.success(function(responses) {
this.latest = responses;
});
});
<div class="announcements" ng-controller="onBusinessAnnouncementCtrl as announcements">{{announcements.latest}}</div>

How to generate links in Angular UI Bootstrap Pagination

I have been continuing learning angular and have now used the angular ui bootstrap pagination successfully. I am able to display the list of items together with the correct number of pages. And also switch to the correct page whenever I click on the pagination.
Now my question is if a user wanted to bookmark a certain page, or to make sure the user stays on the same page whenever he refreshes the browser, how do I go about it. There are no links (href) being generated on the address bar of the browser. Do I also need to set routes? Can you please post some examples, as it would greatly help me. Thanks.
You need to set up routes, you can do it using routeProvider or ui router
In this example, I use route provider to demonstrate, but the idea is the same.
Here I set up a route with currentPage as parameter:
app.config(function($routeProvider) {
$routeProvider
.when('/page/:currentPage', {
templateUrl: "template.html",
controller: PaginationDemoCtrl
})
});
In your controller, you can retrieve the current page from $routeParam:
$scope.currentPage = $routeParams.currentPage || 1; //default to 1 if the parameter is missing
//load your paged data from server here.
You could just $watch current page for changes and update the location accordingly:
$scope.$watch("currentPage",function(value){
if (value){
$location.path("/page/" + value);
}
})
Source code
DEMO link
With routing, you also need to update your code to load paged data from server. We don't load data immediately when the currentPage changes (in this case is the $watch function). We load our paged data when we retrieve the $routeParam.currentPage parameter.
As requested by #Harry, here is another solution to generate href links by overwriting bootstrap html template:
app.config(function($routeProvider) {
$routeProvider
.when('/page/:currentPage?', {
templateUrl: "template.html",
controller: PaginationDemoCtrl
})
})
.run(["$templateCache","$rootScope","$location", function($templateCache,$rootScope,$location) {
$rootScope.createPagingLink = function(pageNumber){
return "#" + $location.path().replace(/([0-9])+/,pageNumber);
//Here is a sample function to build href paths. In your real app, you may need to improve this to deal with more case.
}
$templateCache.put("template/pagination/pagination.html",
"<ul class=\"pagination\">\n" +
" <li ng-if=\"boundaryLinks\" ng-class=\"{disabled: noPrevious()}\"><a ng-href=\"{{$root.createPagingLink(1)}}\">{{getText('first')}}</a></li>\n" +
" <li ng-if=\"directionLinks\" ng-class=\"{disabled: noPrevious()}\"><a ng-href=\"{{$root.createPagingLink(page - 1)}}\">{{getText('previous')}}</a></li>\n" +
" <li ng-repeat=\"page in pages track by $index\" ng-class=\"{active: page.active}\"><a ng-href=\"{{$root.createPagingLink(page.number)}}\">{{page.text}}</a></li>\n" +
" <li ng-if=\"directionLinks\" ng-class=\"{disabled: noNext()}\"><a ng-href=\"{{$root.createPagingLink(page + 1)}}\">{{getText('next')}}</a></li>\n" +
" <li ng-if=\"boundaryLinks\" ng-class=\"{disabled: noNext()}\"><a ng-href=\"{{$root.createPagingLink(totalPages)}}\">{{getText('last')}}</a></li>\n" +
"</ul>");
}]);
Source code
DEMO link
We can do this with the $location, without needing $route.
Here is an example of how to call the pagination from Angular UI Bootstrap:
<pagination ng-model="Controls.currentPage"
total-items="Controls.totalItems"
items-per-page="Controls.videosPerPage"
max-size="5"
rotate="false"
boundary-links="true"
ng-change="pageChanged()">
</pagination>
Inside the pageChanged() function, use the following to create a unique URL for your results page:
** My code is on Coffeescript, but the logic is simple and the code easy to adapt **
$location.search('page', $scope.Controls.currentPage)
And on your controller, use the following to check, when starting, if the URL parameter is there:
urlParams = $location.search()
if urlParams.page?
$scope.Controls.currentPage = urlParams.page
else
$scope.Controls.currentPage = 1
Yes, if you want your app to allow linking into certain states then you will have to have your app leverage the routeProvider.
The official docs don't have a great deal of information on routes but the tutorial has this page:
http://docs.angularjs.org/tutorial/step_07
Also John Lindquist's excellent short video tutorials are a must watch. One dealing with routes is:
http://www.egghead.io/video/gNtnxRzXj8s
Here the generic solution - the uibPagination directive decorator and the updated template:
angular.module('ui.bootstrap.pagination')
.config(function($provide) {
$provide.decorator('uibPaginationDirective', function($delegate, $templateCache) {
var directive = $delegate[0];
directive.scope.getPageHref = "&";
$templateCache.put("uib/template/pagination/pagination.html",
"<li ng-if=\"::boundaryLinks\" ng-class=\"{disabled: noPrevious()||ngDisabled}\" class=\"pagination-first\"><a ng-href=\"{{noPrevious() ? '' : getPageHref()(1)}}\" ng-disabled=\"noPrevious()||ngDisabled\" uib-tabindex-toggle>{{::getText('first')}}</a></li>\n" +
"<li ng-if=\"::directionLinks\" ng-class=\"{disabled: noPrevious()||ngDisabled}\" class=\"pagination-prev\"><a ng-href=\"{{noPrevious() ? '' : getPageHref()(page - 1)}}\" ng-disabled=\"noPrevious()||ngDisabled\" uib-tabindex-toggle>{{::getText('previous')}}</a></li>\n" +
"<li ng-repeat=\"page in pages track by $index\" ng-class=\"{active: page.active,disabled: ngDisabled&&!page.active}\" class=\"pagination-page\"><a ng-href=\"{{getPageHref()(page.number)}}\" ng-disabled=\"ngDisabled&&!page.active\" uib-tabindex-toggle>{{page.text}}</a></li>\n" +
"<li ng-if=\"::directionLinks\" ng-class=\"{disabled: noNext()||ngDisabled}\" class=\"pagination-next\"><a ng-href=\"{{noNext() ? '' : getPageHref()(page + 1)}}\" ng-disabled=\"noNext()||ngDisabled\" uib-tabindex-toggle>{{::getText('next')}}</a></li>\n" +
"<li ng-if=\"::boundaryLinks\" ng-class=\"{disabled: noNext()||ngDisabled}\" class=\"pagination-last\"><a ng-href=\"{{noNext() ? '' : getPageHref()(totalPages)}}\" ng-disabled=\"noNext()||ngDisabled\" uib-tabindex-toggle>{{::getText('last')}}</a></li>\n" +
"");
return $delegate;
});
});
We decorate the directive with the getPageHref function passed from the outer scope which is used to construct the page links.
Usage:
<div ng-controller="ProductController">
...
<ul uib-pagination
total-items="totalItems"
ng-model="page"
get-page-href="getPageHref">
</ul>
</div>
Now you have to define the getPageHref function in your outer scope:
angular.module('app')
.controller('ProductController', function($scope) {
...
$scope.getPageHref = function(page) {
return '#/products?page=' + page;
};
});
Just to make code look better you can use template-url attribute on uib-pagination element
to specify your new template url
I whould use ui-sref instead of using a function to generate the link .
and instead of reloading the controller for each page click pass a function for ng-click with $eventso you could prevent the href from been executed
with e.preventDefault() and calling your ajax before
<li ng-repeat="page in pages track by $index" ng-class="{active: page.active}"><a ui-sref="list({page: page.text})" ng-click="$root.paginationClick(page.number,$event)">{{page.text}}</a></li>

Categories

Resources