Skip to content

Instantly share code, notes, and snippets.

@SayChunKim
Created February 23, 2017 23:40
Show Gist options
  • Save SayChunKim/c504509e604f2f475fe3d3390406b742 to your computer and use it in GitHub Desktop.
Save SayChunKim/c504509e604f2f475fe3d3390406b742 to your computer and use it in GitHub Desktop.
Data Passing when Angular DOM is ready via GET URL Params (with $viewValue)
// DATA PASSING TO INPUTS when Document Ready
// SITUATION: ngModel != $viewValue <input type="text" name="food_name" ng-model="part1.food_name">
angular.element(document).ready(function($event) {
// Get CURRENT URL Params (May replace with $http request
var url = $location.search();
console.log(url);
// Get name attribute of form element
console.log($scope.userForm);
$scope.$apply(function() {
// Loop of Objects of url params exp: {'name':'John Doe','favourite_food':'Spagetti'}
Object.keys(url).forEach(function(key) {
// Update $viewValue of scope example $scope.userForm.name.$viewValue
$scope.userForm[key].$viewValue = url[key];
// Update Commit all form controls pending updates to the $modelValue
$scope.userForm[key].$commitViewValue();
console.log($scope.userForm[key]);
// Update value of elements such as textarea or input
document.getElementsByName(key)[0].value= url[key];
// Set $dirty and $touched for interaction of data
$scope.userForm[key].$setDirty();
$scope.userForm[key].$setTouched();
});
// $apply calls $digest automatically
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment