construct url in angularjs directive - javascript

I made a directive for automatically add links for a html validation, like that :
.directive('validationhtml', function($rootScope, $location) {
return {
restrict: 'A',
template: 'validation html',
controller: function($scope, $location) {
$scope.getUrl = function() {
var url = 'http://validator.w3.org/check?uri=' + $location.path;
console.log(url);
return url;
}
}
};
})
createTab(); is a function in rootscope, and correctly executed (new tab), but getUrl(); have a problem: the url is not good, in the return i have this
http://validator.w3.org/check?uri=function (c){if(B(c))return this[b];this[b]=a(c);this.$$compose();return this}
what's wrong ?

It should be location.path().

$location path is a function:
var url = 'http://validator.w3.org/check?uri=' + $location.path();

Related

How to make document ready conditional using AngularJS?

I'm using ASP.NET MVC and AngularJS as my framework. I've a link which send request to MCV Action and finally gets forwarded to view. This view has registered JavaScript File which loads angular.element(document).ready(function (e){} function. Basically I'm trying to create a if else statement inside angular.element(document).ready. based on myparam=true. How can I do it?
Link -
"<h7>" + "" + "<a target=\"_blank\" href='/Submission/EditSubmissionFile?id=" + SubmissionID + "&myparam=true" +"'>" + "Add Attachment" + "</a><br></h7>" +
AngularJS Javascript File -
mainApp.controller('editSubmissionFileController', ['$scope', '$location', '$http', 'viewDataService', 'utilityService', '$window', 'constants', '$timeout', 'constants', 'adComplianceUtility', 'submissionRuleService',
function ($scope, $location, $http, viewDataService, utilityService, $window, constants, $timeout, constants, adComplianceUtility, submissionRuleService) {
angular.element(document).ready(function (e) {
// How to make this conditional based on parameter passed from Action or html link?
$scope.$broadcast('ShowFileUpload', {
SubmissionID: $scope.model.data.SubmissionID,
Show: true,
Callback: function (data) {
$scope.onFileUploadSuccessful(data);
}
})
});
}
Action -
public ActionResult EditSubmissionFile(int id)
{
// We can only see what we are allowed
UserContext.TestSubmissionExists(id);
UserContext.TestSubmissionAccess(id, AccessRightEnum.ViewSubmissions);
var model = _submissionSvc.GetSubmissionViewModel(id);
return View("EditSubmissionFile", model);
}
Adding a simple window.location.href and check if parameter exists in URL does the job. Sometimes simple is better! Thank you.
angular.element(document).ready(function (e) {
// Check if URL contains a parameter value to restrict default pageload function.
if (window.location.href.indexOf("myparam=true") > -1)
{
$scope.$broadcast('ShowFileUpload', {
SubmissionID: $scope.model.data.SubmissionID,
Show: true,
Callback: function (data) {
$scope.onFileUploadSuccessful(data);
}
})
}
});

Enabling ng-click to open a link in browser window

I have ng-click producing a valid url from my data but struggling to get to open in a browser window, as this will trigger my 3rd party app to open.
I have tried some options and got a few extra button options(2-6) i have found on Stack and Google, can anyone help with getting it to open in a browser?
Here is an image of app showing the console output when I click on the full width button and the code in a Plunker.
http://i.imgur.com/0tfxTuE.jpg
https://plnkr.co/edit/WBYfa3m19MAwobtdbdfU
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic','ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('tabs', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
.state('tabs.home', {
url: '/home',
views: {
'home-tab' : {
templateUrl: 'templates/home.html'
}
}
})
.state('tabs.list', {
url: '/list',
views: {
'list-tab' : {
templateUrl: 'templates/list.html',
controller: 'ListController'
}
}
})
.state('tabs.detail', {
url: '/list/:aId',
views: {
'list-tab' : {
templateUrl: 'templates/detail.html',
controller: 'ListController'
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/home');
})
.controller('ListController', ['$scope', '$http', '$state','$cordovaBluetoothSerial', '$location', function($scope, $http, $state, $cordovaBluetoothSerial, $location) {
$http.get('js/aboDATAONLY.json').success(function(data) {
$scope.orders = data;
$scope.whichorder = $state.params.aId;
})
function onPay() {
var itemsArr = [];
var invoice = {};
var myItems = {};
var myItem = {};
myItem['name'] = "Sphero";
myItem['description'] = "A robotic ball that can be controlled via apps";
myItem['quantity'] = "1.0";
myItem['unitPrice'] = "129.00";
myItem['taxRate'] = '0.0';
myItem['taxName'] = 'Tax';
itemsArr.push(myItem);
myItems['item'] = itemsArr;
invoice['itemList'] = myItems;
invoice['paymentTerms'] = 'DueOnReceipt';
invoice['currencyCode'] = 'GBP';
invoice['discountPercent'] = '0';
invoice['merchantEmail'] = 'myemail#mail.com';
invoice['payerEmail'] = 'foo#bar.com';
var returnUrl = 'http://wp1175175.wp220.webpack.hosteurope.de/speedhack/index.html';
var retUrl = encodeURIComponent(returnUrl + "?{result}?Type={Type}&InvoiceId={InvoiceId}&Tip={Tip}&Email={Email}&TxId={TxId}");
var pphereUrl = "paypalhere://takePayment/v2?returnUrl=" + retUrl;
//var pphereUrl = "paypalhere://takePayment/?";
pphereUrl = pphereUrl + "&accepted=cash,card,paypal";
pphereUrl = pphereUrl + "&step=choosePayment";
pphereUrl = pphereUrl + '&invoice=' + escape(JSON.stringify(invoice));
console.log(pphereUrl);
return pphereUrl;
}
$scope.pay = function () {
window.location = onPay();
};
}]);
give a try with
var url = onPay();
window.open(url , '_blank');

Caching internationalization JSON data in AngularJS

Here i am created multi-language concept in my application its working fine, but language (.json) file loaded for every field, So application taking time to load, my requirement is i want to load .json only once to fetch all the data , how to do in angularJs, Thanks for your help in advance
please check the below link also
http://plnkr.co/edit/PYZxcI5yTNuA0fEern9s?p=preview
var language = 'en';
app.directive('telBasictext', ['$http', 'teli18nservice',
function($http, teli18nservice) {
return {
restrict: 'AEC',
require: 'ngModel',
scope: {
ngModel: '=',
},
template: '<div class="form-group" > ' +
'<label > {{ setvalue }} </label> ' +
'<div > <input type="{{ textboxtype }}" ng-model="ngModel" ></div></div>',
link: function(scope, iElement, iAttrs, ngModelController) {
var collecton = iAttrs.getString;
var splitValues = collecton.split(",");
var language = splitValues[0]; // Language EN or Fr
var labelName = splitValues[1]; // Label Name
var moduleName = splitValues[2]; // Module Name (global or local)
teli18nservice.getdata(moduleName).success(function(data) {
scope.setvalue = data[labelName];
})
.error(function(error) {
scope.setvalue = "No Label";
});
}
};
}
]);
Store the result of a request for the JSON locally in your teli18nservice service and return that data for subsequent calls to getdata. It would look something like this:
// teli18nservice
var jsonData;
this.getData = function () {
if (jsonData) {
return $q.resolve(jsonData);
}
$http.get().then(function (res) {
jsonData = res.data;
return jsonData;
});
}
Alternatively, take a look at caching $http responses.
May be you should use the cache of $http.
example taken from here:
var cache = $cacheFactory('myCache');
var data = cache.get(someKey);
if (!data) {
$http.get(url).success(function(result) {
data = result;
cache.put(someKey, data);
});
}

Angular JS - dynamic url params and custom url access redirect

I'm just trying to get this to work:
.....
.when('/channel/:id/:slug',{
templateUrl:'views/channel/index.html',
controller:'Channel',
publicAccess:true,
sessionAccess:true
})
.....
app.controller('Channel', ['$scope','$routeParams', function ($scope,$routeParams) {
}]);
app.run(function($rootScope, $location, $route) {
var routesOpenToSession = [];
angular.forEach($route.routes, function(route, path) {
console.log(path);
console.log(route);
route.sessionAccess && (routesOpenToSession.push(path));
});
$rootScope.$on('$routeChangeStart', function(event, nextLoc, currentLoc) {
var closedToSession = (-1 === routesOpenToSession.indexOf($location.path()));
if(closedToSession && $rootScope.session.id_user) {
$location.path('/');
}
});
});
why i can't access the page via site.com/channel/9/my-slug also if $rootScope.session.id_user exists and sessionAccess:true ?
i get redirected to / , while any other static url are ok using sessionAccess:true for example channel/staticparam is ok but with dynamic params it won't work
this is the console log result :
fixed sorry for the stupid question:
/*Not logged redirects*/
app.run(['$rootScope','$location','$route', function ($rootScope, $location,$route) {
var routesOpenToPublic = [];
angular.forEach($route.routes, function (route, path) {
if(route.publicAccess){ routesOpenToPublic.push(route.regexp); }
});
$rootScope.$on('$routeChangeStart', function (event, nextLoc, currentLoc) {
var next_url_regexp = nextLoc.$$route.regexp;
//redirect for not logged users users
if(routesOpenToPublic.indexOf(next_url_regexp) < 0){
$location.path('/auth/login');
}
});
}]);
/*Logged redirects*/
app.run(['$rootScope','$location','$route', function ($rootScope, $location, $route) {
if($rootScope.session && $rootScope.session.id_user){
var routesOpenToSession = [];
angular.forEach($route.routes, function (route, path) {
if(route.sessionAccess){ routesOpenToSession.push( route.regexp);}
});
$rootScope.$on('$routeChangeStart', function (event, nextLoc, currentLoc) {
var next_url_regexp = nextLoc.$$route.regexp;
//redirect for not allowed session users
if(routesOpenToSession.indexOf(next_url_regexp) < 0){
$location.path('/');
}
});
}
}]);
i needed to check the route regexp and not the static url path

Scope are not updated AngularJS

I'm sad... I cook porridge of the ax..
Please, if you can - help me deal with my problem.
I have this structure in my html code(ng-controller is on wrap tag):
<a ng-repeat="subitem in cur_submenu" ng-href="#/{{subitem.href}}/">{{subitem.name}}</a>
In JS I have:
1) RouteProvider
$routeProvider.
when('/:lvl1', {
template:'<div ng-include="htmlUrl">Loading...</div>',
controller: 'MainCtrl'
})
2) Controller
function MainCtrl($scope, $http, $routeParams){
var lvl = window.location.hash.split('/');
if ($scope.submenu) {
//if data was fetch earlier, then set currentMenu
$scope.cur_submenu = $scope.submenu[lvl[1]];
} else {
MainCtrl.prototype.fetchData();
}
MainCtrl.prototype = {
fetchData: function(){
/*
* Get data about navigation
*/
$http({method: 'GET', url: 'data/main.json'}).
success(function(data){
$scope.menu = data.menu;
$scope.submenu = data.submenu;
$scope.cur_submenu = data.submenu[lvl[1]] //current submenu for my location
});
}
}
But it is not updating on my page, when I changed my location on a website(hash-nav)... Please help my. Full version of my site: http://amiu.ru
You don't need to add a function to your Controller with prototyping. Functions called in your view are to be declared on the $scope like so:
function MainCtrl($scope, $http, $routeParams){
var lvl = window.location.hash.split('/');
if ($scope.submenu) {
//if data was fetch earlier, then set currentMenu
$scope.cur_submenu = $scope.submenu[lvl[1]];
} else {
$scope.fetchData();
}
$scope.fetchData = function(){
/*
* Get data about navigation
*/
$http({method: 'GET', url: 'data/main.json'}).
success(function(data){
$scope.menu = data.menu;
$scope.submenu = data.submenu;
$scope.cur_submenu = data.submenu[lvl[1]] //current submenu for my location
});
};
}
In all other cases, if you're executing changes on a $scope outside of a $scope function, you'll need to manually call $scope.$apply() to queue a digest and update your view.

Categories