$scope variable not reloaded - angularjs

In the controller I have the code below :
//View
<input type="text" value="{{customer.lastName}}" />
//Controller
$scope.getbycode = function (customerCode) {
var deferred = $q.defer(),
getCustomerRequest = {
code: customerCode
};
$http({ method: 'POST', url: 'api/customer/getbycode', data: getCustomerRequest })
.success(function (data) {
deferred.resolve(data);
}).error(function () {
deferred.reject();
});
return deferred.promise;
};
$scope.getbycode($routeParams.customerCode).then(function (data) {
$scope.customer = data.customer;
});
That's work, I see the lastname of Customer.
In the controller I have this code too. This function is called when I ckick on an hyperlink
$scope.reload = function (customerCode) {
$scope.getbycode(customerCode).then(function (data) {
$scope.customer = data.customer;
alert($scope.customer.lastName);
});
};
I change the text in the input and I click on the hyperlink.
The WEBAPI is called, the data returned in the reload function is correct but the view is not updated.
I missed something ?

value="{{customer.lastName}}" will only evaluate expression first time & then it replaces with customer.lastName value which is 1, DOM will look like below
<input type="text" value="1" />
Which had got rid off {{customer.lastName}} value, the changes in scope variable will never happen to that input field.
You should use ng-model there to have two way binding, that will update input & scope value once you update scope value.
<input type="text" ng-model="customer.lastName" />
Demo Plunkr

Related

angularjs ---- In the following code, I can not get the value of avatarPath

console log
angular.module('Kinder.pages.member')
.controller('MemberInfoCtrl', MemberInfoCtrl);
function MemberInfoCtrl($scope,MemberModel,Constants,fileReader,$filter,AppUtils,$http,toastr,API) {
var vm = this;
vm.member = {};
vm.member.memberType = "1";
vm.member.memberSex = "1";
vm.member.avatarPath = "";
$scope.getFile = function () {
fileReader.readAsDataUrl($scope.file, $scope);
var fileInput = document.getElementById('uploadFile').files[0];
if(!AppUtils.isUndefinedOrNull(fileInput)){
var formData=new FormData();
formData.append("picUrl",fileInput);
$http({
........
}).success(function(data, status) {
console.log(data);
if(data.stat == 'success'){
//vm will have avatarPath value in there
console.log(vm);
vm.member.avatarPath = data.path;
//vm will have avatarPath value in there
console.log(vm);
}
}).error(function(data, status) {
});
}
};
$scope.submit = function() {
//vm had loss avatarPath ...
console.log(vm.member);
};
}
I do the function is to upload pictures before the preview, upload to the server to return to the path, assigned to vm。
But I can not get the avatarPath value outside the $ scope.getFile method。
I suspect that the problem of the scope of the problem, but I can not find a solution, I am the angular novice。
So who can tell me what this is for the reason。
I used google translation to describe the above questions,
I do not know if you understand me。。。
Anyway, thank you for taking the time to browse this question!
i fix it!
thanks for #JayantPatil reminders!
i am declaring controller in the route
.state('member.info', {
url: '/info/{memberId:string}',
params: {
memberId: null
},
templateUrl: 'app/pages/member/info/member-info.html',
controller: 'MemberInfoCtrl as vm'
});
and in the html , i use the ng-controller
<div class="userpic" ng-controller="MemberInfoCtrl as vm">
<input type="file" ng-show="false" id="uploadFile" ng-file-select/>
</div>
cause i duplicate declarations the controller , maybe the Scopes is Different,
that is all

Angular 1.5 - Clear form after submit

I have read through all of the suggested postings on this, but I can't seem to clear the form fields after I submit.
I am using controller as syntax, but even if I try to use $scope with $setPristine, I still can't make it work.
This SO answer is what I am following:
https://stackoverflow.com/a/37234363/2062075
When I try to copy this code, nothing happens. No errors, nothing is cleared.
Here is my code:
app.controller('HiringRequestCtrl', function ($http) {
var vm = this; //empty object
vm.ctrl = {};
vm.saveChanges = function() {
//console.log(vm);
$http({
method: 'POST',
url: '/hiringrequest/createPost',
data: angular.toJson(vm)
})
.success(function (response) {
//great, now reset the form
vm.ctrl = {};
})
.error(function (errorResponse) {
});
}
});
and my form looks like this:
<div ng-controller="HiringRequestCtrl as ctrl">
<form id="form" name="ctrl.myForm">
...
<input type="text" name="proposalName" ng-model="ctrl.proposalName"/>
<input type="submit" id="saveButton" value="Submit" class="button" ng-click="ctrl.saveChanges()" />
...
</form>
</div>
I would really prefer not to use $scope.
There's some fundamental issues with the way you've structured this. I think your use of vm.ctrl and then also ng-controller="HiringRequestCtrl as ctrl" is confusing you. Below are my recommended [untested] changes. (I would also suggest moving the $http stuff into a service and using .then() and .catch() because .success() and .error() are deprecated).
Controller
.controller('HiringRequestCtrl', function($http) {
var vm = this; // self-referencing local variable required for when promise resolves
vm.model = {};
vm.saveChanges = function() {
$http({
method: 'POST',
url: '/hiringrequest/createPost',
data: angular.toJson(vm.model)
})
.success(function(response) {
//great, now reset the form
vm.model = {}; // this resets the model
vm.myForm.$setPristine(); // this resets the form itself
})
.error(function(errorResponse) {});
}
});
HTML
<div ng-controller="HiringRequestCtrl as ctrl">
<form id="form" name="ctrl.myForm" ng-submit="ctrl.saveChanges()" novalidate>
<input type="text" name="proposalName" ng-model="ctrl.model.proposalName" />
<input type="submit" id="saveButton" value="Submit" class="button" />
</form>
</div>
Update
Service
.service('hiringService', function($http) {
var service = {};
service.createPost = function(model) {
return $http({
method: 'POST',
url: '/hiringrequest/createPost',
data: angular.toJson(model)
});
}
return service;
}
Controller
.controller('HiringRequestCtrl', function(hiringService) {
vm.saveChanges = function() {
hiringService.createPost(model)
.then(function(response) {
// if you need to work with the returned data access using response.data
vm.model = {}; // this resets the model
vm.myForm.$setPristine(); // this resets the form itself
})
.catch(function(error) {
// handle errors
});
}

How to set value string datetime (from database) to <input type="date" ng-model="endtime" name="endtime" />

As my question, this is my first time using angularjs. I try to search the solution but nothing give extactly i want.
i have list data, when update row, row value will be added to table, with datetime column, when i edit, the value can not be set to date picker (angular).
My code.
html input tag:
<input id="endtime" type="date" ng-model="endtime" />
Controller.js
$scope.editJob = function (job) {
debugger;
var getData = EmployeeService.getJobByID(job.JobID);
getData.then(function (emp) {
$scope.job = emp.data;
$scope.endtime = job.EndTime;
;
},
function () {
alert('Error in getting records');
});
}
Service.js
// Update Job
this.updateJob = function (job) {
var response = $http({
method: "post",
url: "Employee/UpdateJob",
data: JSON.stringify(job),
dataType: "json"
});
return response;
}
Index page
index
My string datetime value like : "3/1/2016"
p/s: sorry for my bad english.
If u are using Html input type date. Then assign that variable with new Date("03/25/2015");
go through this link: http://plnkr.co/edit/HcXL2TptB90skqdQznvz?p=preview
Try this
$scope.editJob = function (job) {
debugger;
var getData = EmployeeService.getJobByID(job.JobID);
getData.then(function (emp) {
$scope.job = emp.data;
$scope.endtime = $scope.job.EndTime;
;
},
function () {
alert('Error in getting records');
});
}

Display Angular Loading Bar in a specific $http request NOT in the whole module

When I used the chieffancypants loadingBar, the loading bar appears from the start of the loading of the page and to every $http request that i make,
I want to display only the loading bar progress when I click the search button which retrieves a large amount of data.
var mtg = angular.module('mtgApp',['ui.bootstrap','chieffancypants.loadingBar','ngAnimate']);
mtg.controller('mtgController',function($scope,$http,$location)
{
var apiBaseUrl = "http://sampleAPIURL.com";
$scope.token = "sampletoken";
$scope.processForm = function()
{
$http({
method: 'POST',
url: apiBaseUrl + 'flight/search?token=' + $scope.token,
data: {
//my json request
//flightForm.from,
//flightForm.to,
//flightForm.date
}
}).success(function(data, status, headers, config){
$scope.displayResults(data.searchId);
}).error(function(data, status, headers, config){
console.log("Check For Errors");
});
}
$scope.displayResults = function(searchId)
{
$http.get(apiBaseUrl + 'Flight/results/'+searchId+'?$top=50&token=' + $scope.token).success(function(data)
{
$scope.results = data.flightResult;
$location.path('/search/results');
});
};
});
In my search
<form ng-controller = "mtgController">
<input type = "text" ng-model = "flightForm.from">
<!--uses $http request to get the suggested location-->
<input type = "text" ng-model = "flightForm.to">
<!--uses $http request to get the suggested location-->
<input type = "text" ng-model = "flightForm.date">
<input type = "button" ng-click = "processForm()" value = "Search">
</form>
In my html search/results
<form>
<div ng-controller = "mtgController">
<div ng-repeat = "result in results">
//{{result.details}} and so on and so on
</div>
</div>
</form>
I want the loading bar appears only when I click the search button while waiting for the response data and go to the results page
Try to add after data:
success: function (test) {
$("#mtg.controller").val('');
$("#success").html(test);
$("#mtg.controller").removeClass("disabled");
}
});
});
});
Also, you can do success: function instead of succes(function for what you already have.

how to show error message which is passed by the server when using $asyncValidators

<ng-form name="myForm">
<div ng-show="myForm.text{{$index}}.$error.printValidator">
you cannot print {{data}} !!
</div>
<div>
<textarea name="text{{$index}}" placeholder="{{textSection.text}}" ng-model="getUserTextSction(textSection.textStyleID, area.userPageText).text" print-validator ng-model-options="{updateOn: 'blur'}"> </textarea>
</div>
</ng-form>
<a ng-disabled="myForm.$invalid" ng-click='completeEditPage("/article/")'>
above is my html code and below is javascript code
angular.module('editorApp')
.directive('printValidator', function ($http, $q,baseService) {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attrs, ngModel) {
var checkPrintable = function (modelValue, viewValue) {
var deferred = $q.defer();
var value = modelValue || viewValue;
var param = {};
param.text = value;
return $http.post(
'/api/edittexts/CheckPrintable/',
param, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
.then(function (response) {
if (response.data.ngChar) {
ngModel.$setValidity('printValidator', false);
alert("you cannot print:"+response.data.ngChar);
deferred.reject(response.data);
}
else
{
ngModel.$setValidity('printValidator', true);
deferred.resolve;
}
return deferred.promise;
});
}
ngModel.$asyncValidators.text = checkPrintable;
}
}
})
the code above worked well.when user typed unprintable characters it shows an error message...
Now I have two questions:
the first one is how can i show the unprintable characters which is passed from the server side (actually it is "response.data.ngChar") in the tag at " {{data}}" ??
(it means ,how to get the deferred.reject's parameters in the html)
the second one is how can i disable the submit botton when there is unprintable characters errors?
I use "ng-disabled="myForm.$invalid"" but it doesnot work.
thank you.
I see you are doing some very complicated stuff for a very easy job.
How i would set this up is something as the following:
<div ng-if="!data">Fetching data...</div>
<div ng-if="data && data.length > 0">Unprintable characters: {{data}}</div>
<a ng-disabled="data && data.length < 1" ng-click="completeEditPage("/article/")">
Your variable 'data' will be set when the data is retrieved asynchronously. When data is being retrieved, $scope.data will be undefined making your div 'fetching data...' visible
When your variable 'data' gets set by the asynchronous function. the fetching data... div will disappear and you can view another div based on the 'data' not being undefined.
Now the only thing you need to do is set $scope.data when your function finishes.
so... $scope.data = response.data;
(Hoping that your response.data is an array)

Resources