Just want to know your idea wht will be my approach on how to store external json data file into a services so that i can inject it into different controllers
Thanks
Try to use ngTranslation module.
with this service you can store the static content(some json file, etc..) outside of the code, and not dirty your controllers/services...
EXAMPLE:
JS:
angular.module('app', ['ng-translation'])
.config(['ngTranslationProvider', function(ngTranslationProvider) {
ngStaticProvider
.setDirectory('/assets/static')
.setFilesSuffix('.json')
.langsFiles({
demo1: 'demo1',
demo2: 'demo2'
})
}]);
//inject to controller
function PanelController($scope, translateFilter) {
$scope.panelContent = translateFilter('key','fileName')
}
HTML:
<!-- use as a filter {{ key | translate: fileName }}-->
<p>{{ key | translate: fileName }}</p>
<!-- use ng-translate directive, similar to ng-bind-->
<p ng-translate="file(key)"></p>
Well, it all depends on the architecture of your application but I guess you could create a factory or service that will store data then simply inject that factory wherever needed.
If the data needs to be persistent, I would use something like localStorage. If it's a really small amount of data and your app cannot support HTML5, I would use cookies.
The more you elaborate the more accurate answer you will get.
Have look at the angularjs tutorial. It specifically address this issue.
First go though http://docs.angularjs.org/tutorial/step_05 where you include the json in controller.
Then follow http://docs.angularjs.org/tutorial/step_11 where it is moved to service.
$http.get() can be used to retrive data from REST urls as well.
Related
I've read multiple places that you can share data across controllers with services/providers/factories. Maybe I interpreted the results of these incorrectly but from what I understand services/providers/factories are an abstraction that can be rerun across controllers providing the same data.
I'd like to get result from a database query once without making the same request over again across different controllers. Do services/providers/factories do this or do I need something like ngStorage or localStorage? Or is there another way I'm not thinking of? I saw a mention of making an initial query at start-up (.run?) but I'm not really sure to get started with that.
To summarise from my comments above...
"I'd like to get result from a database query once without making the same request over again across different controllers. Do services/providers/factories do this..."
Yes. Providers in Angular are singletons so they are all the same instance across the different consumers (controllers, etc). You can store data in them that will last in memory.
A factory only lasts as long as you have the page open and don't reload or navigate away whereas something like local storage persists outside this range.
Here's an example making an HTTP query on app startup (ie, opening / reloading the page) that can be shared across controllers and other consumers
angular.module('so', [])
.factory('sharedData', function($http) {
// this factory is a promise
return $http.get('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.data);
})
.controller('someController', function(sharedData) {
sharedData.then(post => {
this.post = post;
});
})
.controller('anotherController', function(sharedData) {
sharedData.then(post => {
this.post = post;
});
});
<div ng-app="so">
<dl ng-controller="someController as s">
<dt>Post title</dt>
<dd>{{s.post.title || 'Loading...'}}</dd>
<dt>Post body</dt>
<dd>{{s.post.body || 'Loading...'}}</dd>
</dl>
<pre ng-controller="anotherController as a">post = {{a.post|json}}</pre>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
That depends. If you looking for the way to load data only once per application session (e.g. between application bootstrap and window reload/close/navigate outside) services going to be a solution for you. But if you looking for the solution that will also store your data between sessions you need to rely on some browser storage solution inside of your services.
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.
I have a url which has an object which contains name,city then how to display it on a page.
http://www.w3schools.com/angular/customers.php
You can use Angulars $http-Service. It creates a promise which delivers the data and you can use that in your Controller, Service etc.
I created a simple Plunkr which showcases a possible setup.
Code looks something like
$http.get('http://www.w3schools.com/angular/customers.php').success(function(data) {
console.log(data);
});
You can access that data like shown in the Plunkr.
Have fun!
I am thinking of storing error messages in a properties file in my UI framework (angularjs). When a rest call fails, based on the error code I can read the messages from the file and show it on the UI. Similar to how struts handles this through messageresource properties. I tried to look up the angularjs doc but not getting any direction on how to do it. Any suggestions on how to achieve this feature in angularjs?
This is one of the ways to show error messages in your UI.
Create a json file ErrorMessages like this:
{
"ERROR-EDIT": "Some problems by updating the item!",
"ERROR-SAVE": "Some problems by saving the changes!",
"ERROR-DELETE": "Some problems by deleting!",
"ERROR-EMAIL": "E-Mail is not valid!"
}
To get the data from json file, in your controller you have to create http request to that file.
Providing that your module and other angular configuration is valid, the controller should be like:
app.controller('mainController', ['$scope', '$http', function ($scope, $http) {
//HTTP call to get data from file with valid url
$http.get('../Resources/ErrorMessages.json').success(function (data) {
$scope.listMessages = data;
});
}]);
And finally, the key note to display just one property of that object with key-value (explicit way):
<body ng-controller="mainController">
<p>{{listMessages["ERROR-EDIT"]}}</p><br /><br />
<p>{{listMessages["ERROR-DELETE"]}}</p><br /><br />
<p>{{listMessages["ERROR-EMAIL"]}}</p><br /><br />
<p>{{listMessages["ERROR-SAVE"]}}</p><br /><br />
</body>
You could also create function with parameteres including object and key to display it with the same result.
I hope this idea will push you forward :)
Read about http-interceptors in Angular to handle global stuff like that. There is no concept of structs in Angular. Angular tries to keep its core fairly simple and includes only core stuff. You might want to write your own module using http interceptors to handle something like that.
You can write a error log service and inject in all controllers where ever you want to log errors. That service can persist your log to Mongo or wherever
Question: What is the best way and the best time to pre-load .ng files that are used in routing templates?
In researching this thus far, I've found the following answers:
Use Angular's script directive.
Problem: My content cannot be loaded as a literal string but needs to be fetched from the server. In other words, I have an .ng file as my partial so I cannot do
my content must remain in a .ng file on the server and be fetched
Use $templateCache.put to put a template literal in the cache. Same problem as above.
Use $http to load the .ng file. This works in that it is not a string literal but I am struggling to find the best time to perform this so that it is not blocking (realize its async but still)
To save you from suggesting resources I've already seen, I've read the following:
Is there a way to make AngularJS load partials in the beginning and not at when needed?
https://groups.google.com/forum/#!topic/angular/6aW6gWlsCjU
https://groups.google.com/forum/#!topic/angular/okG3LFcLkd0
https://medium.com/p/f8ae57e2cec3
http://comments.gmane.org/gmane.comp.lang.javascript.angularjs/15975
Maybe use a combination of 2 and 3.
Like you said, $http is async, so why not just put each partial into the templateCache after the app has loaded.
For example:
var myApp = angular.module('myApp', []);
myApp.run(function($http, $templateCache) {
var templates = ['template1.ng', 'template2.ng'];
angular.forEach(templates, function(templateUrl) {
$http({method: 'GET', url: templateUrl}).success(function(data) {
$templateCache.put(templateUrl, data);
});
});
});
I've never had the need for this and definitely haven't tested it, but the idea is there.