In my angular app, I have a URL to which I connect for retrieving some data, a CORS enabled server.
Now, so far I had it hardcoded in my javascript file:
server_url = "http://localhost:7888/api.php/json?id=2"
Now, on test and production, those URLs of course are not valid...and everytime I do a git pull it overrides my customizations.
Where would I elegantly put a config like that in an angular app?
Declare it as a constant. Assuming you have an app named App:
angular.module('App', []).constant("urls", {"server_url":"http://localhost:7888/api.php/json?id=2"});
Once declared as a constant, you'd inject it as a dependency, just as you would a service.
well, basically I'd adopt a mean.js approach here, it's quite easy to implement and it could be useful to you or anybody else.
you have to write from your middleware into your main HTML file in angular (ex: index.html), in your case the URL for your endpoint have to change depending on your environment just to keep it simple let's say we have dev (localhost) and production (mydomain.com)
in your index html do a simple write:
<script type="text/javascript">
<?php
if(strpos( $_SERVER['HTTP_HOST'], 'mydomain.com') !== false){
print "var endpoint = '"+ $server_url+ "';"
} else{
print "var endpoint = '"+ $local_url+ "';"
}
?>
</script>
one you got that into your main index.html it's available in angular by using the window object, so you can wrap it into a constant or a service.
this is the example for a constant:
angular.module('app').run(function () {
}).value('endpoint', window.endpoint);
I'm not fluent in PHP, but I hope you can get my point
Related
I had print value issue in laravel view, i was trying to print $scope value inside laravel blade. I searched about and find two kind of solution.
1- Change angularjs print tag
By this method i can change angularjs print tag.
var app = angular.module('app', []);
app.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
app.controller('app', function ($scope, $http) {
$scope.text_print = 'this is text';
});
Now in blade i can print like <% text_print %>
2- Add # for printing angularjs $scope value
I found an up-voted answer in which #Paul A.T. Wilson says that
The easiest way to do this is to simply use # in front of your Angular code
Example #{{text_print}}
Both are working for me, actually i want to make a plugin, so which method should i use? because i'm not sure the second one is compatible with laravel old version. I want my plugin compatible with all version of laravel.
Can anyone guide me about this, i would like to appreciate. Thank You
Changing either interpolation strings for Blade or angular is the best option if you want your plugin to work with older versions of Laravel.
For angularJs you already know how to do it from here.
For Blade, inside your Laravel app's AppServiceProvider.php file add the following code in the boot function:
public function boot() {
Blade::setRawTags("[[", "]]");
// for variables and Blade
Blade::setContentTags('<%', '%>');
// for escaped data
Blade::setEscapedContentTags('<%%', '%%>');
}
Note: In my opinion it's easier to change the interpolation tags for angular as changing the interpolation tags for blade requires you to clear out the storage/framework/views folder.
Apparently there's another way to do this, but I'm not sure if it will work in older versions:
#verbatim
<div>
{{ variableOne }}
{{ variableTwo }}
</div>
#endverbatim
The verbatim annotation indicates that the section is as-is, ie: Blade will leave it out.
Is it possible to get the response object sent by the render() (Symfony2) method?
An example:
public function indexAction(){
$params = array('Hi' =>'Hello world', 'userName' =>'Jack');
return $this->render('exampleBundle:Default:index.html.twig', $params);
}
I'm totally able to capture the var $params and its content in the html.twig file, but I can't figure out how to get that content it in javascript to render the view using angular. Just in case, I tried many absurd things, but they didn't work at all obviously.
Maybe it isn't possible at all and I'll need to redesign it or make a new ajax call once the document is loaded instead of passing the content via the render() method. I'm not really sure so, can I reach this without make an ajax request?
This approach seems to me a bad thing. Most of modern client applications philosophy is to to load as soon as possible the web page from server and the load data through xhr request.
Said that if you need or want to do it, you can achieve it in differents manners:
I did not tried the examples, so this can contains some syntax errors:
1- JS Vanilla approach; in your html.twig
<script type="text/javascript">
window.nameSpaceOfMyApp = window.nameSpaceOfMyApp || {};
window.nameSpaceOfMyApp.exchange = window.nameSpaceOfMyApp.exchange || {};
window.nameSpaceOfMyApp.exchange.params = JSON.parse({{$params |json_encode()}});
</script>
2- More "Angular Way" Not overloading global namespace and better testing...If you have load angular.js at this point you can create in twig template the main module of your angular App (if you cant use your main module, you can use a new module and require it as dependency of your main module)
in your html.twig:
<script type="text/javascript">
angular.module('moduleName',[<dependencies>,...])
.value('exchange',{
params: JSON.parse({{$params |json_encode()}})
})
</script>
Later you can inject this value where you need it.
angular.module('moduleName').controller('nameOfController',['exchange', function(exchange){
console.log(exchange.params)
}]);
I have a script at the bottom of the index.html file within an Angular app that I want to change based on an environment variable in Node. I want to use one public api key with staging and another with production.
I use the same grunt build for both staging and production, so I don't know if dynamically changing the constants on build as suggested here is the best solution.
Any thoughts on how to handle this?
When environment variable is NODE_ENV=production, insert this:
<script>
Stripe.setPublishableKey('pk_live_NN4j94VX3mtz2wJtIO3bmH');
</script>
When environment variable is NODE_ENV=staging, insert this:
<script>
Stripe.setPublishableKey('pk_test_LgtEvbZwjC2GaKQYE3I6NnzuA');
</script>
I would use grunt-ng-constant to manage your angular environment variables and then initialize Stripe inside of your angular app.config() function rather than your document.
My preference is to manage Stripe inside the angular boot process using angular-stripe. This also may make your life easier if you configure your application with both keys. Here's some example code from one of my applications.
var $app = angular.module('app', ['angular-stripe']);
$app.constant('devDomains', ['localhost', 'staging.mydomain.com']);
$app.constant('stripePubKeyStaging', 'STRIPE_PUB_KEY_HERE');
$app.constant('stripePubKey', 'STRIPE_PUB_KEY_HERE');
$app.config(function(devDomains, stripePubKey, stripePubKeyStaging, stripeProvider) {
if (devDomains.indexOf(document.location.hostname) !== -1 || document.location.search.indexOf('stripe-test-key') !== -1) {
// if you're running your angular app on local or staging, use the test key. Additionally
// if you load your page with ?stripe-test-key you can force your production app
// to use the test key in order to debug something on live if you'd like.
stripeProvider.setPublishableKey(stripePubKeyStaging);
} else {
stripeProvider.setPublishableKey(stripePubKey);
}
});
Is there a way in angularjs to dynamically (after angular bootstrap) to enhance a service by proxying it using the decorator pattern.
In the following plunker example I can overload my default search service (google based) but this relies on the declaration/addition of the overloading module (the yahoo one) using the app.requires dependencies of the application before the angular app is bootstrapped. This does not work once the angular application is already bootstrapped, as demoed when clicking on duckduckgo button.
I must do the decoration dynamically by injecting javascript code into the application in a migration scenario where the webapp has to be embed into a java client (using JavaFX webview) and where some actions (the ones introduced dynamically) have to replace standard behavior of the webapp.
I have tried to use some technics described by Ifeanyi Isitor in his blog without success.
One possible method might be to get a hold of the injector of the currently running application (as described at the bottom of the documentation for angular.injector). This is done by using angular.element on an element of the currently running app to get its injector().
To easily get a hold of this element, if you were to give the tag on which you've declared your app the id of mcfoggy-application-search:
<div ng-app="mcfoggy.application.search" id="mcfoggy-application-search">...</div>
... you could .getElementById() and clobber the originally defined service a bit like this (as per your plunkr):
console.info('interpreting duckduckGoService.js');
var appElement = document.getElementById('mcfoggy-application-search');
var injector = angular.element(appElement).injector();
injector.invoke(['SearchService', '$log', function(SearchService, $log) {
// replace search in SearchService
SearchService.search = function(terms) {
var duckduckGoSearch = 'https://duckduckgo.com/?q=' + encodeURI(terms);
$log.info("search called: " + duckduckGoSearch);
// $window.location.href = duckduckGoSearch;
};
}]);
Maybe not as pretty as decoration, but it seems to work!
Updated plnkr
I basically want to use tel tag to make a phone call.
<a class="callButton" href="tel: {{phoneno}}"></a>
I am using $compileProvider to remove unsafe tag which comes by default, It works perfectly fine post 1.0.4v of angularjs. However below this version it doesnt work. Can anyone suggest how to implement this feature using angular version 1.0.4 or below?
Here is the sanitizing code which I am using in js file
app.config(['$compileProvider', function ($compileProvider) {
$compileProvider.urlSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
}
Assume I have already defined app variable.
P.S. This is an enhancement for particular app which basically works below 1.0.4v
Thanks
Add this to your scripts after angular is loaded.
I asume your on 1.1.5, but change to whatever you need the version to be.
http://code.angularjs.org/1.1.5/angular-sanitize.min.js
Example:
sanitizeSomething = function(string) {
return $sanitize(string);
};
sanitizedString = sanitizeSomething(string);