I am in a new Backbone.js . I need to send some variables with save function in my app. For example:
myModel.save({variabl1,variabl2,..}, {
success: function() {}
});
Variable is not related myModel. But I don't know how to do it. If You know how to do it, please, tell me!
you can pass parameters in the options has of save method.
myModel.save(
{variabl1,variabl2,..},
{ success: function() {},
data: {param1: 'value1', param2: 'value2' }
});
I found the way :
myModel.save( null, {
headers: {param1: 'value1', param2: 'value2' },
success: function() {}
});
Maybe anyone will useful the code.
Related
I'm working on a website with angular ui-router. There is a page which needs to pass some parameters to another view. I defined my states like this:
.state('locaties', {
url: "/locaties",
data: {rule: function($cookieStore) {} },
controller: "FranchisesCtrl",
templateUrl: "view/locaties.html"
})
.state('locaties.detail', {
params: {
locatieID: 1,
locatieName: "Derptown",
locatieLat: 50,
locatieLong: 50
},
url: "/:locatieName",
controller: "LocatieDetailCtrl",
templateUrl: "view/locatie.html",
resolve: {
locatiedetail:
function ($stateParams, $http){
var url ="http://website/api/franchises/" + $stateParams.locatieID + "/nl.json";
return $http.get(url).then(function(res){
return res.data;
});
}
}
})
Inside LocatieDetailCtrl there's this
angular.module('PremiumMeat').controller('FranchisesDetailCtrl',
function ($scope, $window, franchisedetail) {
$scope.franchiseDetail = franchisedetail;
});
The "Locaties" (plural) view works properly and when I click on a specific "locatie" (single), the url changes and the view gets loaded within the locaties view and no parameters are passed. On the image you can see the top 2 items from the "locaties" view. Then a single locatie is loaded under the "locaties" view. This should be a new page (view) with the parameters from the clicked locatie. Can anyone help me / explain, I'm rather new to angular, thank you.
Solution
The parameters where hard-coded, to make them dynamic, syntax needed adjustment according to angular docs.
params: {
locatieID: {value : "1"},
locatieName: {value : "Stad"},
locatieDescr: {value : "Beschrijving"},
locatieLat: {value: 51.2},
locatieLong: {value : 4.4}
},
Where parameters are passed with ui-href like this
<a ui-sref="locaties.detail({
locatieID: item.id,
locatieName: item.name,
locatieDescr: item.description,
locatieLat: item.location[0].lat,
locatieLong: item.location[0].long
})"
class="detail">Bekijk detail >></a>
The 'params' defined should return the key-value pair object.
But it is a better practice if you are passing values from one state to another to use 'data' instead of appending everything in the URL.
The following code should work :
//The following values are default values of the parameters
.state('locaties.detail', {
params: {
locatieID: '1',
locatieName: 'Derptown',
locatieLat: '50',
locatieLong: '50'
}, ........
This should work. The values expected are of string type and not number.
As far as your LocatieDetailCtrl is concerned, you need to inject what you have in the resolve of the 'locaties.detail' state (i.e. 'locatiedetail'). So your 'LocatieDetailCtrl' should look like following:
angular.module('PremiumMeat').controller('FranchisesDetailCtrl',
function ($scope, $window, franchisedetail, locatiedetail) {
$scope.franchiseDetail = franchisedetail; //make sure you have franchiseDetail as well.
$scope.locatiedetail = locatiedetail;
});
I hope that will work.
I am currently developing a little app with Angular and MEAN.js.
I would like to plot a D3 chart with some real data coming from the model.
To do so, I would have to read from the $scope.campaign variable and initialize the $scope.dataBarChart with the data from $scope.campaign.tokens that is an array.
// Find existing Campaign
$scope.findOne = function() {
$scope.campaign = Campaigns.get({
campaignId: $stateParams.campaignId
});
$scope.dataBarChart = [
{
'key': 'Token Requested',
'values': [['10.10.2014', 550000], ['11.10.2014',300000]]
}, {
'key': 'Token Consumed',
'values': [['10.10.2014', 250000], ['11.10.2014',200000]]
}
];
};
When I try to log the value of $scope.campaign, I get all the data that I need. Unfortunately, when I try to access the $scope.campaign.tokens, I get an error like impossible to access tokens from undefined value. Basically, it seems that there is no data, but I know from the log that is not like this.
The complete code is simply the same, but with a console.log line
// Find existing Campaign
$scope.findOne = function() {
$scope.campaign = Campaigns.get({
campaignId: $stateParams.campaignId
});
console.log($scope.campaign)
$scope.dataBarChart = [{
'key': 'Token Requested',
'values': [['10.10.2014', 550000], ['11.10.2014',300000]]
}, {
'key': 'Token Consumed',
'values': [['10.10.2014', 250000], ['11.10.2014',200000]]
}];
};
The console.log shows the right content, but when I try to use it $scope.campaign.tokens, it says undefined.
Anyone suggestions?
Thanks
Try
$scope.campaign.$promise.then(function(data) {
console.log(data.tokens)
});
I'm trying to make an AJAX call with ngResource, In the code below 'a' and 'b' both print, but the AJAX call from Table.import() does not get made. If I move the AJAX call outside of onFileRead, then it works. What could be the problem?
var TableImportController = ['$scope','Table', 'project', 'table',
function($scope, Table, project, table) {
$scope.table = table;
$scope.project = project;
$scope.onFileRead = function(file) {
console.log('a');
Table.import({ data : file.data}, function() {
}, function() {
});
console.log('b');
};
}];
Where Table is an ngResource
.factory('Table', function($resource) {
var Table = $resource('/api/tables/:id:listAction/:itemAction',
{
id: '#id',
listAction: '#listAction',
itemAction: '#itemAction'
},
{
update: { method: 'PUT' },
import : { method: 'POST', params: { listAction: 'import' }},
}
);
return Table;
});
You are declaring $scope.onFileRead as a function.
What is calling onFileRead?
When you move the call outside of the function, it is being run as part of initialization.
What provides the input file?
Probably bind to the onFileRead function from something in your DOM.
I figured it out. It looks like I ran into this bug: https://github.com/angular/angular.js/issues/2794#issuecomment-18807158.
I solved the issue by wrapping the AJAX call (and eventually moved it to where the onFileRead callback is triggered) in a scope.$apply(function() { });
I am trying to build a search application using ExtJS. I have created dummy form to search for personal details. I have a php script connected to mysql DB. I am able to pass form parameters to php and able to get the return result in msg box. but I am not understanding how to pass it to store and display the same in grid in MVC. I have tried to pass the return data of php to store and then called Grid (List.js) in controller. still did not work. I have shown all the codes that i have used to do this.Another doubt which i have, is that essential to use proxy part of code (i.e url:app/scripts/Info.php) in both store and onSearchButtonClick function in controller? as I can directly pass the return values to store from onSearchButtonClick function, I hope it is not essential to connect php script in both places. However, it would be really nice experts clarify this.
Following is my store:
Ext.define('App.store.Info', {
extend: 'Ext.data.Store',
model: 'App.model.Info',
alias: 'widget.infostore',
pageSize : 50,
autoLoad : false,
remoteFilter: true,
proxy :{
type : 'ajax',
url : 'app/scripts/Info.php',
reader : {
type : 'json',
root : 'result',
successProperty : 'success'
}
},
listeners: {
load : function(store) {
store.each(function(record) {
record.commit();
});
}
}
});
My model looks perfect, simply to reduce somuch code I havent put here
Here is my grid:
Ext.define('App.view.info.List' ,{
extend: 'Ext.grid.Panel',
alias : 'widget.infolist',
store : 'Info',
initComponent: function(){
this.columns = [
{header:'PID',dataIndex:'pid'},
{header:'Name',dataIndex:'name'},
{header:'Address', dataIndex:'address'},
{header:'Contact', dataIndex:'contact'}
];
this.callParent(arguments);
}
});
This is what my php script returns:
{'success':true, 'result':{'pid':'100','name':'Suman','address':'Bangalore','contact':'suman#xyz.com'}}
Here is controller:
Ext.define('App.controller.Info', {
extend: 'App.controller.Base',
models: ['Info'],
stores: ['Info'],
views: [
'info.Index',
'info.List'
],
refs: [{ref: 'info',selector: 'info'}],
init: function(){
console.log('Main controller init');
this.control({
'button[action=search]':{
click: this.onSearchButtonClick
}
});
},
onSearchButtonClick:function(){
var form = Ext.getCmp('ppanel');
if(form.getForm().isValid()){
Ext.Ajax.request({
waitMsg: 'Searching...',
method: 'POST',
url: 'app/scripts/Info.php',
params: {
searchData: Ext.encode(form.getValues())
},
scope:this,
success: this.onSearchSuccess,
failure: this.onSearchFailure
//Ext.MessageBox.alert("XXXXX","dat");
});
}
},
onSearchSuccess: function(response){
var gData = Ext.JSON.decode(response.responseText);
//var grid = Ext.widget('infolist'); //not working -need help
this.getInfoStore().load(gData);
//Ext.getCmp().setActiveItem('infolist'); //not working-need help
//this.getViewport().getLayout().setActiveItem('infolist'); //not working need help
Ext.MessageBox.alert("XXXXX",response.responseText); //works
},
onSearchFailure: function(err){
Ext.MessageBox.alert('Status', 'Error occured during searching...');
}
});
I hope I have provided required information to understand the problem. Looking forward some sort of help.
The problem is that you have two instances of the store, one in grid and one in controller.
If you want a single instance store (like it seems you want) you have two options:
Add it to your application
Assign a storeId to your store definition.
(if you already added that store to your application, ignore the above text)
Or, better yet, do not work directly with the store but with your grid, like this:
First add a ref to your view->grid in your controller:
refs: [{ref: 'info',selector: 'info'},{selector:'infolist', ref:'infoGrid'}]
And then, in your onSearchSuccess handler, instead of calling: this.getInfoStore().load(gData); you should call: this.getInfoGrid().getStore().loadData(gData);
BTW: this.getInfoStore().load(gData); will never load an array of data or a record, for that you should use: this.getInfoStore().loadData(gData);
Hope this gets you in the right track.
I have variable $scope.data= [{column:"age", operator: ">", value: "50"}, {column:"name", operator: "=", value: "Tonda"}]. And service for submitting data to server:
angular.module('myServices', ['ngResource']).
factory('serverApp', function($resource, $scope){
return $resource('myurl/', {}, {
saveData: {method:'POST', params: $scope.data}
});
});
Why URL contains "nonsense" after calling `serverApp.saveData()? - .../myurl?0=%5Bobject+Object%5D&1=%5Bobject+Object%5D - It seems, that params can be only simple (1D) object.
How can I properly serialize object $scope.cfgcondition into params of service serverApp (eg. to URL)? Thanks.
The 'params' attribute defines URL query params, which I assume is intended behavior. If it was just a simple object, not an array, then you could just use $save something like
var MyRequest = $resource('/notreally');
$scope.data = new MyRequest;
// get stuff into $scope.data
$scope.doSubmit = function() { $scope.data.$save(); }
To post an array you need to define your own action and pass the data in as second parameter.
$scope.data= [{column:"age", operator: ">", value: "50"},
{column:"name", operator: "=", value: "Tonda"}];
var MyRequest = $resource('/notreally', {}, {saveData: {method:'POST', isArray: true}});
$scope.doSubmit = function() { MyRequest.saveData({}, $scope.data);
http://docs.angularjs.org/api/ngResource.$resource
https://docs.angularjs.org/api/ngResource/service/$resource
*Edited to fix misstatements regarding arrays - I thought $resource could not POST arrays, but figured out that I was wrong!