I want to bind dropdowns in edit mode but with value selected according to each record
My Edit View
<select ng-model="user.StateId" ng-init="user.StateId=#Model.StateId" data-ng-options="s.Id as s.State for s in States " data-ngchange="GetCities()"></select>
<select ng-model="user.CityId" data-ng-options="c.Id as c.City for c in Cities " ></select>
My Angular Js
function GetStates() {
$http({
method: 'Get',
url: '/Home/GetStates'
}).success(function (data, status, headers, config) {
$scope.States = data;
}).error(function (data, status, headers, config) {
$scope.message = 'Unexpected Error';
});
}
$scope.GetCities = function (obj) {
var stateId = $scope.user.StateId;
alert(stateId);
if (stateId) {
$http({
method: 'POST',
url: '/Home/GetCities/',
data: JSON.stringify({ stateId: stateId })
}).success(function (data, status, headers, config) {
$scope.Cities = data;
}).error(function (data, status, headers, config) {
$scope.message = 'Unexpected Error';
});
}
else {
$scope.states = null;
}
}
$scope.edit = function (user) {
var ref = user;
$http
({
method: 'GET',
dataType: 'html',
url: location.href = '../Home/Edit?Id=' + ref.Id,
})
}
Now when user click on edit i want to open user details in edit mode and i m doing so using $scope.edit user is my object in which i m getting data to edit now i want dropdown of edit view to show state and city selected as per the state and city i got as a response in function(user)
Related
I have a drop-down menu populated with ng-options.
<label class="item item-input item-select">
</div>
<div class="input-currencies">
Select Currency
<select ng-options="c.code as c.name for c in currencies" ng-model="codeMod" ng-change="currencyChange(codeMod)">
</select>
</label>
How do I get the value c.code to be the property of the variable named selectedCurrency?
.controller('CurrencyController', function($scope, $http) {
var ngb_currencies = 'http://lari.jumpstart.ge/en/api/v1/nbg_currencies?callback=JSON_CALLBACK'
var selectedCurreny = "" // I want get dropdown code in this variable depending on the selected currency so I make changes in the API
$http.jsonp(ngb_currencies).success(function(currency) {
$scope.currencies = currency.results;
})
.error(function(data) {
alert("ERROR");
});
$http({
method: 'jsonp',
url: 'http://lari.jumpstart.ge/en/api/v1/nbg_rates?callback=JSON_CALLBACK',
params: { currency: selectedCurreny }
}).success(function(data, status , header, config) {
console.log('success');
$scope.result = data.result;
console.log('success');
}).error(function(data, status , header, config) {
console.log('error');
});
First, you have to change c.code as c.name for c in currencies in the ng-options attribute, you can't use a property here, it becomes c as c.name for c in currencies
Then, since you specified ng-model="codeMod", you can watch that variable in your controller, which becomes the following :
.controller('CurrencyController', function($scope, $http) {
var ngb_currencies = 'http://lari.jumpstart.ge/en/api/v1/nbg_currencies?callback=JSON_CALLBACK'
$http.jsonp(ngb_currencies).success(function(currency) {
$scope.currencies = currency.results;
})
.error(function(data) {
alert("ERROR");
});
$scope.$watch('codeMod', function(newSelectedCurreny) {
$http({
method: 'jsonp',
url: 'http://lari.jumpstart.ge/en/api/v1/nbg_rates?callback=JSON_CALLBACK',
params: { currency: newSelectedCurreny}
}).success(function(data, status , header, config) {
console.log('success');
$scope.result = data.result;
console.log('success');
}).error(function(data, status , header, config) {
console.log('error');
});
}
}
.controller("HttpPostController", function ($scope, $http)
{
console.log('SendHttpPostData login', $scope.loginData);
$scope.SendHttpPostData = function ()
{
var data =
{
name:$scope.loginData.username,
pwd:$scope.loginData.password
}
var config =
{
headers : {
'Content-Type': 'application/json;charset=utf-8;'
}
}
$http.post('demo url', data, config)
.success(function (data, status, headers, config)
{
console.log(" success"+status);
})
.error(function (data, status, header, config)
{
console.log(" error"+status);
});
};
This is my code , I have called function SendHttpPostData() on
ng-submit="SendHttpPostData()" in html file and added ng-controller in div properly than to i am getting 404 error whenever SendHttpPostData() is called,Please help me.
Try this if it may help you. But you haven't defined demo_url.
var demo_url = 'http://facebook.com:8081';//whatever your url is
$http({
method: 'POST', url: demo_url, data: { name:$scope.loginData.username, password: pwd:$scope.loginData.password },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).success(function (data, status, headers, config)
{
console.log(" success"+status);
})
.error(function (data, status, header, config)
{
console.log(" error"+status);
});
I am new in Angular JS. I have written a script that open a modal box. There are few buttons in that modal box on which I want to apply the click event.
Below I have mentioned my code:
angular.module("vss_shoppingcart_modal",["ui.bootstrap","dialogs","ngSanitize"]).controller("vss_shoppingcart_dialogService",function($scope,$dialogs,$sce){
$scope.init = function(){
dlg = $dialogs.create("/dialogs/whatsyourname.html","vssShoppingCartCTRL",{},{key: false,back: "static"});
};
}) // end dialogsServiceTest
.controller("vssShoppingCartCTRL",function($scope,$sce,$http,$modalInstance,data){
$http({
method: "GET",
url: "' . $url . '"
}).
success(function(data, status, headers, config) {
$scope.trustedHtml = $sce.trustAsHtml(data); // Apply the html to modal
});
$scope.cancel = function(){
$modalInstance.dismiss("canceled");
}; // end cancel
$scope.removeProduct = function(event){
$http({
method: "GET",
url: event.target.id
}).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
// or server returns response with an error status.
});
}; // End removeProduct
$scope.updateQuantity = function(event){
$http({
method: "POST",
url: "' . $this->getUrl('shoppingcartpopup/index/updateCart') . '",
data: { "product_id": event.target.id, "qty": "2", "update_cart_action":"update_qty"}
}).
success(function(data, status, headers, config) {
$http({
method: "GET",
url: "' . $url . '"
}).
success(function(data, status, headers, config) {
$scope.trustedHtml = $sce.trustAsHtml(data);
});
}).
error(function(data, status, headers, config) {
// or server returns response with an error status.
});
}; // End updateQuantity
}) // end whatsYourNameCtrl
.run(["$templateCache",function($templateCache){
$templateCache.put("/dialogs/whatsyourname.html","<div class='ngModal' ng-bind-html='trustedHtml'></div>");
}]);// end run / module
On page load, I have passed a static block to modal window then by ajax request, I have updated the content again.
I don't know how to apply ng-click event on button in my view file.
In view, I have a link button -
<a href="javascript:void(0);" class="dialog-titlebar-close" role="button" ng-bind="cancel()" ng-click="cancel()">
<span class="header_close_icon">close</span>
</a>
ng-click is not working on this link.
I am trying to access the http headers in my angular controller but I am getting undefined. Also, I am able to see the header response in my angular service which is not reflecting in my controller. Can someone please tell me what I am missing? Please see the code below:
Service:
cmApp.service('supplierService', function ($http, $q) {
this.getSuppliers = function (orderByColumn, skipRows, takeRows) {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'api/supplier',
params: { orderBy: orderByColumn, skip: skipRows, take: takeRows },
timeout: 30000,
cache: false
}).
success(function (data, status, headers, config) {
// any required additional processing here
deferred.resolve(data, status, headers, config);
}).
error(function (data, status) {
deferred.reject(data, status, headers, config);
});
return deferred.promise;
}
Controller:
supplierService.getSuppliers($scope.orderby, $scope.skip, $scope.take)
.then(function (data, status, headers, config) {
**//getting undefined here.**
$scope.totalRecords = parseInt(headers('X-TotalRowCount'));
$scope.suppliers = data;
}, function (error) {
// error handling here
});
I have found the solution by myself. All I have to do is create an array and add all those values to the same & return it to the controller. Please see the updated code below:
Service:
cmApp.service('supplierService', function ($http, $q) {
this.getSuppliers = function (orderByColumn, skipRows, takeRows) {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'api/supplier',
params: { orderBy: orderByColumn, skip: skipRows, take: takeRows },
timeout: 30000,
cache: false
}).
success(function (data, status, headers, config) {
// any required additional processing here
var results = [];
results.data = data;
results.headers = headers();
results.status = status;
results.config = config;
deferred.resolve(results);
}).
error(function (data, status) {
deferred.reject(data, status, headers, config);
});
return deferred.promise;
}
Controller:
supplierService.getSuppliers($scope.orderby, $scope.skip, $scope.take)
.then(function (response) {
$scope.suppliers = response.data;
$scope.totalRecords = parseInt(response.headers["x-totalrowcount"]);
}, function (error) {
// error handling here
});
This question is old, but $http() returns a promise itself. you can just return that from your service, no need to create a new promise. You can do this even after using .success() and .error(), or for that matter even after using a .then(), they keep chaining.
I had to access Token and TokenExpiry time from response headers of my Rest Service,then store it in my $rootScope.
Here is the code I used:
$scope.Authenticate=function(){
var EncDecUserPass=decodeURIComponent(encodeURIComponent($scope.LoggedUserName+':'+$scope.LoggedUserPassword)) ;
$http(
{method: 'GET',
url: 'http://localhost:53256/api/Products/Authenticate',
cache: false,
headers:{'Authorization':'Basic '+window.btoa(EncDecUserPass)}
}
).success(function(data, status, headers, config) {
//Here it goes
$rootScope.token=headers().token;
$rootScope.tokenExpirySec=headers().tokenexpiry;
}).error(function(data, status, headers, config) {
alert('Invalid User');
});
}
I have a loading icon set up on my page that looks like this:
<div class="loading-mask"
data-ng-show="action != null">
<span>{{action}} ...</span>
</div>
When I set $scope.action to a message appears in the loading box.
When loading my page I have a number of different async processes that get data. For example I have:
getUserProfiles: function ($scope) {
var url = '/api/UserProfile/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.userProfiles = data;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
},
and:
getSubjects: function ($scope) {
var url = '/api/Subject/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.subjects = data;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
},
How can I make it so that the first of these async processes causes a "Loading" message to appear and the last of the async process causes the loading box to not show any more. Note at this time I am not concerned about error messages. I just want the loading to not show when everything is completed.
To expand on what devmiles has said, but to handle the multiple asynchronous functions, you will want to set a loading flag on your first function to be called. I.e.:
getUserProfiles: function ($scope) {
$scope.loading = true;
var url = '/api/UserProfile/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.userProfiles = data;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
},
And then you will want to wrap each of your asynchronous functions in a promise, like so:
getUserProfiles: function ($scope) {
var deferred = $q.defer();
$scope.loading = true;
var url = '/api/UserProfile/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.userProfiles = data;
deferred.resolve();
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
deferred.reject();
});
return deferred;
},
You can then call $q.all on all of your asynchronous functions, and the success callback of this will occur once all asynchronous functions have resolved:
$q.all([getUserProfiles, getSubjects]).then(function() {
$scope.loading = false;
}
This means once all of your functions have resolved, loading will be set to false.
NB: If you want to access the data of your callbacks, you can pass it in as a parameter of "deferred.resolve(x)", and then in your $q.all callback, it will be available as function(x) { do something with x }.
Hope this helps!
EDIT: Don't forget to pass in angular's promise service, $q, to the controller where your functions are.
Just set some boolean flag on when your controller is being instantiated and reset this flag in your success/error functions.
.controller('MyCtrl', function ( $scope ) {
$scope.isLoading = true;
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.subjects = data;
$scope.isLoading = false;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
$scope.isLoading = false;
});
});
Use ng-show with this flag to show your loading thingy.