I've got an array in my scope and I am iterating over each element with an input in the html template:
Controller:
app.controller("otherArticleCtrl", ["$scope", "$http", function($scope, $http) {
$scope.articles = [{ url: 'index.php', title: "First"}, { url: 'index.php', title: "Second"}];
}]);
Template:
<div ng-repeat="(key, article) in articles track by $index">
<h1>{{ article.title }}</h1>
<input type="text" ng-model="article.url"/>
</div>
I need when user modifies the url in the input, make an AJAX get call, and update the article title.
I've made a watch function looping through the array:
for(var i=0; i < $scope.articles.length; i++) {
$scope.$watch('articles['+i+'].url', function(new, old){
if(new != old){
$http({
method: 'GET',
url: new
}).then(function successCallback(response) {
$scope.articles[i].title = response.title;
});
}
}, true);
}
But $scope.articles[i] is undefined and I don't know how to get the reference of the model or element that is changed.
Any ideas? Thanks for help.
Should not use $watch in any loop. In this case you can use ng-change instead of $watch. and send index number in ng-change function. like ng-change="changeUrl($index)". and function shown in bellow.
can try:
In html:
<div ng-repeat="(key, article) in articles track by $index">
<h1>{{ article.title }}</h1>
<input type="text" ng-model="article.url" ng-change="changeUrl($index)"/>
</div>{{index}}
In controller:
$scope.articles = [{ url: 'index.php', title: "First"}, { url: 'index.php', title: "Second"}];
$scope.changeUrl = function(index){
$http({
method: 'GET',
url: $scope.articles[index].url
}).then(function successCallback(response) {
$scope.articles[index].title = response.title;
});
};
you can use $http.get
$http.get($scope.articles[index].url)
.then(function(response) {
$scope.articles[index].title = response.title;
});
I'd suggest using ngChange instead.
You can do something like this :
<input type="text" ng-model="article.url" ng-change="somethingChanged()"/>
And add the function inside your controller. If you need to know the index of the element that changed you can use $index from the ng-repeat to know where is the data that changed :
<input type="text" ng-model="article.url" ng-change="somethingChanged($index)"/>
$scope.somethingChanged = function(index) {
$scope.articles[index]; <--------- Here is the element that changed
}
Happy coding!
Related
I get the response from POST, it prints the data in the console but it doesn't show the data in the html page.
I have my controller, its just that the {{user}} doesnt show in html page
I can see the what it returns in the console,
angular.module('app.AllUsersCtrl', [])
.controller('AllUsersCtrl', function ($scope, $http, $cookies, $window, $state) {
$scope.getAccount = function (n) {
$http({
method: 'POST',
url: '/FYPapp/getAccount',
data: $.param({
username: n
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
}).success(function (data, status, headers, config) {
console.log(JSON.stringify(data));
$scope.user = JSON.stringify(data);
});
};
});
**Data Returns **
scripts.js:95 {"id":118,"firstname":"Lauren","lastname":"Smithss","description":"the Makup Chair the.....","enabled":true,"user":{"userid":21,"username":"theMak","email":"theMak22#mail.com","password":"995bf49114defd4f35d10e477135b89112ecdc2f25af6ab7969112842919ba4dc193b194f9485671","enabled":true},"followers":[],"username":"theMak"}
HTML: This is the html page
<link rel="stylesheet" type="text/css" href="static/app/css/css.scss">
<div class="mainDiv">
<h1> Profile Details</h1>
{{user}}
</div>
In your HTML you need to define our controller with ng-controller and also the ng-app which will be your module name.
Then you will need to make the data call.
After that you can directly assign the data to scope like this:
$scope.user = data;
As it appears you're using a controller alias, ie
.state('profile', {
url: "/profile",
templateUrl: '/views/profile.html',
controller: 'AllUsersCtrl',
controllerAs: 'allusers' // this one here
})
You should be assigning methods and properties to the controller instance, eg
.controller('AllUsersCtrl', ['$http', function($http) {
var ctrl = this;
this.getAccount = function(n) {
$http(...).then(function(response) {
ctrl.user = response.data;
});
};
}])
and in your template...
<img ng-click="allusers.getAccount(something)"...
and
<h1>Profile Details</h1>
<!-- for debugging -->
<pre>{{allusers.user | json}}</pre>
<!-- or for prod -->
<p>{{allusers.user.firstname}} {{allusers.user.lastname}}</p>
You are missing ng-controller in your html templates.
<h1> Profile Details</h1>
{{user}}
HTML
<form ng-controller="updatecontroller" ng-submit="updateUser()"><label class="control-label">First Name</label>
<input type="text" ng-model="user.userFirstName">
<label class="control-label">Last Name</label>
<input type="text" ng-model="user.userLastName" ><button type="submit" ng-click="updateUser()">Update</button>
</form>
JS
app.controller('updatecontroller', function ($scope, $http, $cookieStore) {
$http.get('http://localhost:8080/myapp/user/'.concat($scope.getUserId) + '?access_token=' + $cookieStore.get("access_token")).
then(function (response) {
$scope.user = response.data;
});$scope.user = {"id": "","userFirstName": "","userLastName": ""}
$scope.updateUser = function () {
var url = "http://localhost:8080/myapp/user/".concat($scope.getUserId) + "?access_token=" + $cookieStore.get("access_token");
var method = "PUT";
$http({
method: method,
url: url,
data: angular.toJson($scope.user),
headers: {
'Content-Type': 'application/json'
}
})
};});
values will appear in text field. i have to update. the values are getting updated in database. but what i want is.. the updated values should not clear after submit the form.
Thanks!
You can empty the input filed after get the response from HTTP request
$scope.updateUser = function () {
$http({
method: 'POST',
url: 'myUri',
data: 'your data'
headers:'header'
}).then(
function(res) {
$scope.user = {"id": "","userFirstName": "","userLastName": ""} //clear the input field here
},
function(err) {
}
);
}
Place your Submit Button inside the Form Element then try it it will clear the input after the submission.
your updateUser() method seems to be the problem. It's probably clearing user.userFirstName & user.userLastName (or the whole user)
please show us what updateUser() is doing to be sure
I used mechanism for transferring state ui-router. With state "inputcontract" that I have defined, when processed (http://cem.survey.local/#/inputcontract/SGD621262), it will pass parameter "sohd" to function "$scope.getSurveyContent($scope,sohd)" in controller "accountController" , this function will send the request to the server to retrieve data returns in json structures. The problem is that I cannot bind value to view by using $scope with json return "$scope.account =response.data_cusinfo[0]", if bind successfully it will appear dynamic on view HTML. How can i do that? Thank you very much.
Here is app.js
var app = angular.module('outbound', ['ngMaterial', 'ui.router'])
.constant('API_URL', 'http://cem.survey.local/');
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('inputcontract', {
url: "/inputcontract/:sohd",
controller: 'accountController'
})
})
Here is accountController.js
app.controller('accountController', function ($scope, $http,$templateRequest, $sce, $compile, $mdDialog, $mdSidenav, $mdMedia, API_URL, $stateParams) {
if (typeof $stateParams.sohd === 'undefined') {
return;
}
$scope.account = {};
var sohd=$stateParams.sohd;
$scope.getSurveyContent= function($scope,sohd)
{ var url = API_URL + "account/search";
$http({
method: 'POST',
url: url,
data: {sohd: sohd},
headers: {'Content-Type': 'application/json'}
}).success(function (response) {
$scope.account =response.data_cusinfo[0];
}).error(function (response) {
});
}
//Send Request to server with sohd
$scope.getSurveyContent($scope,sohd);
Here is the view
<html lang="en-US" ng-app="outbound">
...
<div ng-controller="accountController">
...
<td style="width: 150px">Khách hàng
<div class="form-group">
<input class="form-control" id="inputdefault" type="text"
ng-model="account.CustomerName" >
</div></td>
<td>CMND
<div class="form-group">
<input class="form-control" id="inputdefault" type="text"
ng-model="account.Passport" >
</div>
</td>
<td>Ngày tháng năm sinh
<div class="form-group">
<input class="form-control" id="inputdefault" type="text"
ng-model="account.Birthday">
</div></td>
...
</div>
...
</html>
Assuming the $http post is successful, you don't need to pass $scope on your getSurveyContent function. Also, success and error are deprecated - you should use then. Try this:
$scope.getSurveyContent = function(sohd) {
var url = API_URL + "account/search";
$http({
method: 'POST',
url: url,
data: {sohd: sohd},
headers: {'Content-Type': 'application/json'}
}).then(
function successCallback (response) {
$scope.account = response.data.data_cusinfo[0];
},
function errorCallback (response) {
}
);
}
//Send Request to server with sohd
$scope.getSurveyContent(sohd);
I have a web service which returns json file on call with a parameter for the id of an entry. I have a angular method that returns the data returned from that method. I have no idea how to recall the service when the input of the id has changed as I want to recall that method when a new value has been supplied.
The parameter that I pass in for the Id is called Reference. The HTML returns object with a reference of 1234 but if I change the value I dont know how to recall the service.
This is what I have so far:
Angular:
var app = angular.module("myModule", [])
.controller("myController", function ($scope, $http) {
var res = $http({
method: 'GET',
url: 'AirPortrWebService.asmx/DashboardDetail',
params: { Reference : '1234' }
})
.then(function (response) {
$scope.booking = response.data
});
$scope.test = "Angular Method Called";
$scope.Reference = '1234';
});
Html
<!DOCTYPE html>
<html>
<head>
<script src="scripts/angular.js"></script>
<script src="app/NewAppTwo.js"></script>
</head>
<body ng-app="myModule" ng-controller="myController">
{{test}}
{{Reference}}
<br />
<br />
<input type="text" ng-model="Reference" ng-change="booking"/>
{{booking}}
</body>
</html>
Change ng-change="booking" to a function that is called everytime that models Refences changes:
$scope.getReference = function(referenceNumber){
$http({
method: 'GET',
url: 'AirPortrWebService.asmx/DashboardDetail',
params: { Reference : referenceNumber}
}).function (response) {
$scope.booking = response.data
});
}
<input type="text" ng-model="Reference" ng-change="getReference(Reference)"/>
try this :
var app = angular.module("myModule", [])
.controller("myController", function ($scope, $http) {
$scope.refresh = function(){
var res = $http({
method: 'GET',
url: 'AirPortrWebService.asmx/DashboardDetail',
params: { Reference : $scope.Reference }
})
.then(function (response) {
$scope.booking = response.data
});
}
$scope.test = "Angular Method Called";
$scope.Reference = '1234';
});
and html
<input type="text" ng-model="Reference" ng-change="refresh()"/>
ng-change call the given function each time the input change.
refresh() don't need a parameter because it use $scope.Reference
I'm new to AngularJS.
I want to set it up so that as I type, I send a GET request, but only if what I've typed in the input field is at least three characters long.
Here's index.html:
<html ng-app="myApp">
<div ng-controller="fetchTagsCtrl">
<input type="text" ng-model="userInput.fetchTag" placeholder="Type something">
</div>
</html>
My Javascript:
var app = angular.module('myApp',[]);
app.controller('fetchTagsCtrl',function($scope){
$scope.userInput = {
fetchTag: ''
};
$http({
url: '/myURL',
method: 'GET',
param: {
someParameter: $scope.userInput
}
}).success(function(response){
console.log(response);
})
});
But this doesn't seem to work. How do I fix this?
You must use keyup event for that.
<input type="text" ng-model="userInput.fetchTag" ng-keyup="fetchdata()" placeholder="Type something">
In your controller:
$scope.fetchdata = function() {
// condition to check for characters greater than 3.
if($scope.userInput.fetchTag.length < 4) return;
$http({
url: '/myURL',
method: 'GET',
params : {
someParameter: $scope.userInput
}
}).success(function(response){
console.log(response);
});
}
Also inject $http in your controller.
Your html dom was right. Just simply change would be on your script. Follow the step which provided below
Step 1:
Inject $http to your controller
Ex: app.controller('fetchTagsCtrl',function($scope,$http)
Step 2:
Use $scope.$watch to get your typing event from your input
Let's look at the code below will be look like
var app = angular.module('myApp',[]);
app.controller('fetchTagsCtrl',function($scope,$http){
$scope.userInput = {
fetchTag: ''
};
$scope.$watch('userInput.fetchTag',function(){
$http({
url: '/myURL',
method: 'GET',
param: {
someParameter: $scope.userInput
}
}).success(function(response){
console.log(response);
})
});
});
You can use ng-change directive instead of ng-keyup .because for every change in input it calls to the fetchdata method in controller.
<input type="text" ng-model="userInput.fetchTag" ng-change="fetchdata(userInput.fetchTag)" placeholder="Type something">
$scope.fetchdata = function() {
// condition to check for characters greater than 3.
if($scope.userInput.fetchTag.length > 3)
$http({
url: '/myURL',
method: 'GET',
params : {
someParameter: $scope.userInput
}
}).success(function(response){
console.log(response);
});
}
Watch the model for changes, do a check, then fire your request. Here's how I'd write it:
app.controller('fetchTagsCtrl',function($scope){
$scope.userInput = {
fetchTag: ''
};;
$scope.$watch('userInput.fetchTag',function(value){
if(value.length >= 3){
makeRequest();
}
});
function makeRequest(){
$http({
url: '/myURL',
method: 'GET',
param: {
someParameter: $scope.userInput.fetchTag
}
}).success(function(response){
console.log(response);
})
}
});