I have the following select:
<div class="form-group">
<label class="col-md-4 control-label" for="activity">Activity</label>
<div class="col-md-4">
<select id="activity" name="activity" class="inputsvalues" ng-model="activitymodel.deptid" ng-change="getUsers(activitymodel.deptid)" ng-options="activity.DepartmentId as activity.ActivityDescription for activity in activities"></select>
</div>
</div>
The controller code:
$scope.getUsers = function (id) {
$http({
method: 'GET',
url: 'api/User/GetUsers/' + id,
}).success(function (data, status, header) {
$scope.users = data;
}).error(function (data, status, headers, config) {
$scope.status = status + ' ' + headers;
});
}
The problem is that the ng-change function gets fired the first timeI select something. Second time onwards, it doesnt hit the controller. What could be wrong here?
This is because.. for your code ng-model is same for each value in drop-down. Make ng-model unique for each option. Use $index to achieve this as one of the solutions.
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');
});
}
}
My question is
By deafult I am getting result for 1st hotel, how to get results on onchange of hotels dropdown by using angularjs directives ?
My Code
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app='myApp' ng-controller='HttpController'>
{{detail.name}} <br/>
{{detail.address}} <br/>
{{detail.country}}<br/>
</div>
<script>
var hotelid=$('select#hotel_property option:selected').val();
var data = {};
data.Hotelid = hotelid;
data.Action = "hotel_property";
var helloApp = angular.module("myApp", []);
helloApp.controller("HttpController", function($scope, $http) {
$http({
method: 'POST',
datatype:"json",
header: {
"contentType": 'application/json'
},
data: JSON.stringify(data),
url: '/ajax',
}).success(function(data, status, headers, config) {
$scope.detail = data.hotel_details;
}).error(function(data, status, headers, config) {
alert( "failure");
});
});
</script>
<select id="hotel_property">
<option value="111">Taj hotel</option>
<option value="222">oberoi</option>
<option value="333">JW marriot</option>
<option value="444">Grand Maratha</option>
</select>
By deafult I am getting result for 1st hotel, how to get results on onchange of hotels dropdown by using angularjs directives ?
You'll have to do something on these lines.
Use ng-options to populate hotel list
Use ng-model to bind the selected value to some variable
Use ng-change to trigger a function to handle the change.
<select id="hotel_property" ng-model="selectedHotel"
ng-change="fetchInfo(selectedHotel)"
ng-options="hotel.name for hotel in hotels">
<option value="">-- please select -- </option>
</select>
and your controller might look like this.
Defile $scope.hotels with array of hotel id and name.
define a function to fetch hotel information.
helloApp.controller("HttpController", function($scope, $http) {
$scope.hotels = [{
id: 111,
name:'Taj hotel'
},{
id: 222,
name:'oberoi'
},{
id: 333,
name:'JW marriot'
},{
id: 444,
name:'Grand Maratha'
}];
$scope.fetchHotelInfo(hotel){
var data = {};
data.Hotelid = hotel.id;
data.Action = "hotel_property";
$http({
method: 'POST',
datatype:"json",
header: {
"contentType": 'application/json'
},
data: JSON.stringify(data),
url: '/ajax',
}).success(function(data, status, headers, config) {
$scope.detail = data.hotel_details;
}).error(function(data, status, headers, config) {
alert( "failure");
});
}
});
(Copy pasting code might not work)
Hope this helps!
You can use ng-model directive to store the selected value in the scope and use ng-change to fire the ajax query with the model value as parameter.
https://docs.angularjs.org/api/ng/directive/select
I have an ng-repeat of employees. One of the result fields returned is an employee number e.g. "12345".
How can I perform an ajax lookup and replace the employee number with the corresponding name?
Example: /_api/web/lists/getByTitle('allStaff')/items?$select=fullName&$filter=userid eq '12345'
would return: "Doe, John".
I've tried using a filter but nothing ever gets displayed even though I can see results returned.
<div ng-repeat="emp in employees"">
<i class="fa fa-user"></i> {{emp.id}}
</div>
app.filter('getName', function($http) {
return function(id){
if (id) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('allStaff')/items?$select=fullName&$filter=userid eq '"+id+"'";
$http({
method: 'GET',
url: url,
cache: true,
headers: { "Accept": "application/json;odata=verbose" }
}).success(function (data, status, headers, config) {
userInfo = data.d.results[0].pn;
console.log(userInfo);
}).error(function (data, status, headers, config) {
userInfo = "0";
});
return userInfo;
}
};
});
The filter function is synchronous, while the $http call is asynchronous. The success callback isn't even going to be executed until after the filter function has already returned, so it looks like the return value will be undefined.
An angular filter isn't really appropriate for loading data from an API, and there's an easier approach. Add userInfo to the employees array in the appropriate service/factory/controller (that's up to how you're organizing your code, but the controller where you set $scope.employees is the quick and dirty option). Something like a forEach through the array making an API call for each one and setting employee.userInfo in the success callback:
app.controller('EmployeeController', function($scope, $http) {
// $scope.employees is initialized somehow
$scope.employees.forEach(function (employee) {
if (employee.id) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('allStaff')/items?$select=fullName&$filter=userid eq '"+employee.id+"'";
$http({
method: 'GET',
url: url,
cache: true,
headers: { "Accept": "application/json;odata=verbose" }
}).success(function (data) {
employee.userInfo = data.d.results[0].pn;
}).error(function () {
employee.userInfo = "0";
});
}
});
});
And in your template:
<div ng-repeat="emp in employees">
<i class="fa fa-user"></i> {{emp.userInfo}}
</div>
It's up to you to figure out what to do before the ajax request is finished, while emp.userInfo is undefined - hide the element, show a placeholder, etc.
I'm trying to have an item in HTML update after a successful post query, but I can't seem to get it to work. Here's the HTML side:
<div class='container' ng-controller='MainController as inputControl' >
<div class='row well well-sm'>
<div class='col-md-6'>
<h2>Input Parameters</h2>
<form name='addform' ng-submit='inputControl.mainAddition()'>
<label>Number 1:</label>
<input ng-model='inputControl.inputData.num1' type="number" />
<br>
<label>Number 2:</label>
<input ng-model='inputControl.inputData.num2' type="number" />
<br>
<input type='submit' value='Add them!'/>
</form>
</div>
<div class='col-md-6'>
<h2>Result</h2>
<P>{{inputControl.resultData}}</P>
</div>
</div>
</div>
And here's the Angular side:
angular.module('pageLoader')
.controller('MainController',['$scope', '$http', function($scope, $http) {
var controller = this;
this.inputData = {};
$scope.resultData = 0;
this.mainAddition = (function() {
console.log(this.inputData);
$http({
method: 'POST',
url: '/functions',
data: this.inputData
})
.success( function(data, status, headers, config){
console.log(data);
$scope.resultData= (data);
});
this.inputData = {};
});
}]);
The console log shows the correct response from the server, but the resultData in HTML isn't populating.
Edit:
Yeah, sorry, I totally mixed up $scope and this. Find below working code
angular.module('pageLoader')
.controller('MainController',['$scope', '$http', function($scope, $http) {
this.inputData = {};
this.resultData = 0;
this.mainAddition = (function() {
var cntrlCache = this;
console.log(this.inputData);
$http({
method: 'POST',
url: '/functions',
data: this.inputData
})
.success( function(data, status, headers, config){
console.log(data);
cntrlCache.resultData= data;
});
this.inputData = {};
});
}]);
The easiest way to correct your snippet is to change $scope to controller in
$scope.resultData= (data);
since you've already declared var controller = this in the beginning.
Since the response is a html,you should use inject $sce service in the controller and do the following in the success method of the $http service
$scope.resultData = $sce.trustAsHtml(data)
Also its really a bad practice to have Async methods in the controller.Try to leverage angular services.
Please refer the SO Answer
I can't clarify for myself how to deal with $scope in Angularjs. Although I've resolved my current issue other way, still I need help to get comprehension of $scope usage.
I have the following form (simplified for this example). Index.html:
<form class="form-horizontal" ng-controller="AddItemController as addItemCtrl">
<fieldset>
<legend>New item</legend>
<div class="form-group">
<label for="submittedBy" class="col-lg-2 control-label">Submitted by</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="submittedBy" ng-model="addItemCtrl.item.submitted_by" placeholder="Your name here">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<!--button class="btn btn-default">Cancel</button-->
<button type="submit" class="btn btn-primary" ng-click="addItemCtrl.addItem()">Submit</button>
</div>
</div>
</fieldset>
</form>
app.js:
app.controller("AddItemController", ['$scope','$http', function ($scope, $http) {
$scope.item = {};
this.addItem = function() {
$http({
url: "add_item",
method: "GET",
params: this.item
}).
success(function(data, status, headers, config) {
var table = angular.element($("#body")).scope();
table.items = data;
});
**this.item={};**
}
}]);
All I want is to get data from the form, send it to the server, get response, update table and then clear the form. The last part is my issue. I am currenly using this.item={} to handle it. But I do want to call it using $scope, so it should be $scope.item={} and then I want to move it inside addItem function. Unfortunately it's not working for either case.
I have this code and it is working as intended, but it seems I just got lucky/unlucky to make it without understanding mechanism.
app.controller('ItemController', ['$scope','$http', function ($scope, $http) {
function getItems(){
$http({
url: "get_items",
method: "GET"
}).
success(function(data, status, headers, config) {
$scope.items = data;
});
}
getItems();
}]);`
UPDATE. This is how my AddItemController looks like at the moment:
app.controller("AddItemController", ['$scope','$http', function ($scope, $http) {
$scope.item = {};
this.addItem = function() {
$http({
url: "add_item",
method: "GET",
params: this.item
}).
success(function(data, status, headers, config) {
$scope.$$prevSibling.items = data;
$scope.addItemCtrl.item={};
});
}
}]);
It works like I wanted it to. But I don't like $scope.$$prevSibling.items = data; statement, I use it to refresh table which is handled by ItemController, is there a more elegant way to do that?
You don't have to make getItem function, you can just write $http code and it will just work fine, about $scope, just don't use this, it's kind of tricky here, all the variables you want to make just make it with $scope and get it from $scope like this
$scope.item;
$scope.item.getItem = function(){};
var item1 = $scope.item;
And so on.