I have followed the basics from w3schools: http://www.w3schools.com/angular/angular_sql.asp
I now have controller with this line:
$http.get("getjson.php?q=2")
(let's say it's making a json based on select * from someplace where country=2)
How can I get this dynamic so that I can use the same angular module for all the x countries I want to list? I guess copying the module x times and hard code the country number isn't the best option...
You can crate service that implements your get request
angular.service('someService', function() {
this.getJson = function(qParam){
$http.getjson('getjson.php',{q:qParam});
}
})
you can use it in controller like this
angular.controller('mainController',function(someService){
someService.getjson(2);
})
Related
Please look into my controller
class myController extends Controller
{
$markets = Market::all();
\JavaScript::put([
'markets' => $markets,
]);
return view('test.index');
}
Using this method, I can get all markets in my angularjs file in markets variable.
I saw something like below
class myController extends Controller
{
$markets = Market::all();
return view('test.index', compact($markets));
}
which one would I prefer? what is the advantages of both? what is the difference of both?
1st Method:
It is useful if you want to define your javascript variable from laravel controller method. Then you can use your variable directly into javascript.
console.log(markets);
But problem is you can't call a PHP or laravel function on that variable.
2nd Method:
It's just regular PHP variable declaration and pass the variable to blade template. You can call any php or laravel function on it. But it is not available in javascript.
If you want to make it available.
var markets = "{{ $markets }}";
console.log(markets);
Both have their pros and cons.
I am working on an angularJS project, a music player which can select an album and then play from a list of that album's songs. Everything is working except for that after playing a song from an album(album A) and then selecting another album (album B), when I try to select the previous/next song from a player bar, which is separated from the list, the previous album's (album A) songs play.
Clearly, something is not updating. I read here from a comment by Chev that factories run only once. So, I am thinking the problem might lie with my Songplayer controller(factory).
Here's the code:
AlbumController (the controller with the directive):
....
$rootscope.getAlbumId = $stateParams.getAlbumId;
this.albumData = Fixtures.getAlbum();
this.songPlayer = SongPlayer;
....
FixturesController (factory - serving the music files):
Fixtures.getAlbum = function(){
var chosenAlbum = $rootScope.getAlbumId
return chosenAlbum
....
};
SongPlayerController (factory - playing the music):
....
$rootScope.getAlbumId = $stateParams.getAlbumId;
var currentAlbum = Fixtures.getAlbum();
....
var getSongIndex = function(song){
return currentAlbum.songs.indexOf(song);
};
PlayerBarController:
code same as albumController
It seems the PlayerBarController is not registering the new album from the SongPlayer factory. I have researched and tried using $emit/$broadcast, $watch, various other callbacks, etc... I know the answer is everywhere I have looked but I simply do not have the angular skills yet to figure this out.
Incidentally, I figure my use of $rootScope is also pretty poor, so I am happy to receive advice on that. I used $rootscope and $stateparams in order to capture and register the album id and deliver it to the Fixtures controller.
I think the problem from 'this.albumData = Fixtures.getAlbum();'
You can try:
let albumData = Fixtures.getAlbum();
this.albumData.length = 0;
albumData.map(item => this.albumData.push(item));
I was able to get the PlayerBar controller to register the new album by using $watch. I simply wrapped the call I already had in a $watch function, and voila!
SongPlayer controller:
$rootScope.$watch('getAlbumId', function(album){
currentAlbum = Fixtures.getAlbum();
});
I have seen 100 examples of passing an ID into $resource.get() in order to query information out of a back-end in Angular. What I have not been able to find is how to pass a complex object.
If I have a table of objects to return, and I wish to run a search against them using multiple items of filter, I need to pass those items as parameters or as one complex parameter. For example, say I have a table of people's names and their cities, states, etc. I want to be able to say something like this:
var myResource = $resource(url);
myResource.get({name : "Mike", state : "Texas"});
The return may be a single row or multiple rows. But the point is how do I get the parameters off to the API call?
The way I have other methods set up that are simpler is by creating a repository in which I return like so:
return resource('/api/broker/productionInfo/');
Then in my API I do this (after the [RoutePrefix("api/broker")] setup:
[HttpGet]
[Route("productionInfo")]
public IHttpActionResult GetProductions()
{}
That's all awesome but I want to be able to add the search criteria in the repository call and then in the API method (i.e. extract from a querystring or however it is to be passed).
If I understand what you are asking correctly, you just want to pass additional parameters into an angular resource get request. It is as simple as what you have already suggested:
resource.get({id: 1, custom_param_1: "param1", custom_param_2: "param2"});
This would result in an http request that looks like this:
/resource/1?custom_param_1=param1&custom_param_2=param2
You can then extract these parameters on the API side of things.
Something to note is that get requests have a maximum length, and if you are attaching lots of different parameters to the request, it may be better to use a post or put instead.
The only thing I'm seeing that you're missing is a [FromUri] decorate attribute, in your GetProduction API method. Since Get supports only params binding through a query string (no body binding).
Your params:
options: {
StartDate: _startDate
EndDate: _endDate
TextSearch: "some search query....",
Page: 1,
PageSize: 25,
et...
}
Then, calling your repository from your controller:
repository.get(options).$promise.then(function (data) {
// data = response payload from backend
});
reposiroty
....
return resource('/api/broker/productionInfo/');
....
API
[HttpGet]
[Route("productionInfo")]
public IHttpActionResult GetProductions([FromUri] SearchCriteriaModel criteria) {
....
}
Hope that helps.
There are many duplicated code among CREATE and EDIT controllers.
These controllers could be combined into one for minimizing repetitive code.
The problem: I need to distinguish which method to use on form submitting - create() or edit() for example.
The solution: I could add $scope.mode for example and set $scope.mode='edit' if user clicked 'EDIT' button or set $scope.mode='add' if user clicked 'ADD' button.
I could use services for minimizing repetitive code, but there still will be duplicated code. For example in both controllers I have cancel() method which clears the form and hide it. I could store clearForm() and hideForm() in the service, but this code will be duplicated in both controllers:
$scope.cancel = function() {
Service.clearForm();
Service.hideForm();
};
Questions:
Is it good practice to combine CREATE and EDIT controllers in AngularJS?
Is there any good practices to minimize repetitive code?
Yes. Use 1 controller.
Here is the reason why use 1 controller
The job of the controller is to support the View. Your create view and the edit view is exactly same - just that one has data pre-populated (edit) and another does not (create).
Moreover the "purpose" of this View is to have the user change or enter new values in the form. Your only difference should be something like reset(). But even there you could start with an empty model object e.g. $scope.entity = {} in case of CREATE and you will start with $scope.entity = $http.get().
Repetition Problem with 2 Controllers
With 2 different controllers and services you are going to incur at least the following duplication:
$scope.cancel = function() {
Service.cancel();
};
$scope.validate = function() {
ValidtionSvc.validate();
}
.
.
.//other stuff similar
but the problem is why even this duplication like you stated.
(UDATED here onwards since above was the answer to the 1st question)
How to use 1 controller with repetition ?
Is there any good practices to minimize repetitive code?
Question redefined: Is there a good practice of eliminating repetitive code in CREATE and EDIT forms ?
No formal 'best practice' exist to my knowledge to avoid repetitive code in this specific situation. However I am advising against mode=edit/create. The reason being for controllers in this situation there should be almost no difference since their job is to purely to fetch/update the model as the user interacts.
Here are the difference you will encounter in this situation and how you can avoid if/then/else with mode=create/edit:
1) Populating the form with existing values vs. empty form for Create.
To fetch a existing entities you need some key/query data. If such key data is present you could do
var masterEntity = {};
if(keyData) {
masterEntity = MyEntityResourceFactory.getEntity(keyData);
}
$scope.entity = masterEntity;//for Create this would be {}
2) reset() form
should be simply
$scope.reset = function() {
$scope.entity = masterEntity;
}
3) Update/Create
$http.post()//should not be different in today's world since we are treating PUT as POST
4) Validation - this is a perfect reuse - there should be no differences.
5) Initial / Default Values
You can use masterEntity = Defaults instead of {}.
Is it good practice to combine CREATE and EDIT controllers in
AngularJS?
In my experience, yes it is a good idea for 99.9% of the time. I typically inject a formType variable into my controller via the $routeProvider resolve feature. So I would have something like the following:
$routeProvider
.when('/item/create', {
templateUrl: '/app/item/itemForm.html',
controller: 'itemFormController',
resolve: {
item: ['$route', 'itemRepository', function ($route, itemRepository) {
return itemRepository.getNew();
}],
formType: function () { return Enums.FormType.CREATE; }
},
})
.when('/item/edit/:itemId', {
templateUrl: '/app/item/itemForm.html',
controller: 'itemFormController',
resolve: {
item: ['$route', 'itemRepository', function ($route, itemRepository) {
return itemRepository.get($route.current.params.itemId);
}],
formType: function () { return Enums.FormType.EDIT; },
},
});
That way you get your entity and type of form action injected into the controller. I also share the same templates, so saving a form I can either rely on my repository/service to determine what REST endpoint to call, or I can do a simple check inside the controller depending on what formType was injected.
Is there any good practices to minimize repetitive code?
Some of the things I'm using to keep things DRY:
If you keep a common convention on your server API you can go a very long way with a base factory/repository/class (whatever you want to call it) for data access. For instance:
GET -> /{resource}?listQueryString // Return resource list
GET -> /{resource}/{id} // Return single resource
GET -> /{resource}/{id}/{resource}view // Return display representation of resource
PUT -> /{resource}/{id} // Update existing resource
POST -> /{resource}/ // Create new resource
etc.
We then use a AngularJs factory that returns a base repository class, lets call it abstractRepository. Then for each resource I create a concrete repository for that specific resource that prototypically inherits from abstractRepository, so I inherit all the shared/base features from abstractRepository and define any resource specific features to the concrete repository. This way the vast majority of data access code can be defined in the abstractRepository. Here's an example using Restangular:
abstractRepository
app.factory('abstractRepository', [function () {
function abstractRepository(restangular, route) {
this.restangular = restangular;
this.route = route;
}
abstractRepository.prototype = {
getList: function (params) {
return this.restangular.all(this.route).getList(params);
},
get: function (id) {
return this.restangular.one(this.route, id).get();
},
getView: function (id) {
return this.restangular.one(this.route, id).one(this.route + 'view').get();
},
update: function (updatedResource) {
return updatedResource.put();
},
create: function (newResource) {
return this.restangular.all(this.route).post(newResource);
}
// etc.
};
abstractRepository.extend = function (repository) {
repository.prototype = Object.create(abstractRepository.prototype);
repository.prototype.constructor = repository;
};
return abstractRepository;
}]);
Concrete repository, let's use customer as an example:
app.factory('customerRepository', ['Restangular', 'abstractRepository', function (restangular, abstractRepository) {
function customerRepository() {
abstractRepository.call(this, restangular, 'customers');
}
abstractRepository.extend(customerRepository);
return new customerRepository();
}]);
What you'll find if you use this base repository pattern is that most of your CRUD controllers will also share a lot of common code, so I typically create a base CRUD controller that my controllers inherit from. Some people dont like the idea of a base controller, but in our case it has served as well.
The answer to your first question probably depends on the specific circumstances.
If the two controllers share a substantial amount of operations, and the behavior of just one or two functions needs to be altered - why not! Maybe not the most elegant solution but hey, whatever works.
If the behavior of many or all controller operations is going to depend on '$scope.mode'...I'd say be careful. That seems like a dangerous path.
Angular services have always served me well when it comes to minimizing code replication between controllers. If there is a "good practice to minimizing repetitive code," I would say it would be services. They are global to your app and can be injected into multiple controllers without issue.
I hope that helps!
in my grails app I need to get some data from database and show it in a gsp page.
I know that I need to get data from controller, for example
List<Event> todayEvents = Event.findAllByStartTime(today)
gets all Event with date today
Now, how can I render it in a gsp page?How can I pass that list of Event objects to gsp?
Thanks a lot
You can learn many of the basic concepts using Grails scaffolding. Create a new project with a domain and issue command generate-all com.sample.MyDomain it will generate you a controller and a view.
To answer your question create a action in a controller like this:
class EventController {
//Helpful when controller actions are exposed as REST service.
static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
def showEvents() {
List<Event> todayEvents = Event.findAllByStartTime(today)
[eventsList:todayEvents]
}
}
On your GSP you can loop through the list and print them as you wish
<g:each in="${eventsList}" var="p">
<li>${p}</li>
</g:each>
Good luck
I am not sure if this is really what you meant, because in that case I suggest you to read some more on the grails :), but anyway, for your case you can use render, redirect as well but here I am taking simplest way:
In your controller you have:
def getAllElements(){
List<Event> todayEvents = Event.findAllByStartTime(today)
[todayEvents :todayEvents ]
}
and then in the GSP(I assume you know about grails conventions, as if you don't specify view name, it will by default render gsp page with the same name as the function in the controller, inside views/):
<g:each in="${todayEvents}" var="eventInstance">
${eventInstance.<propertyName>}
</g:each>
something like this.