Getting the value of ng-model input from controller angular js - angularjs

I'm trying to get the value of my ng-model input to my controller. The input value has a value and not empty.
Why this code is not working? It says undefined when you alert or console log. What did i missed? really appreciate your help. here is my code
input --> the value is 1
<input type="text" name="idval" ng-model="Data.idval">
js
app.controller('Controller', function($scope, $http){
$scope.fetchvalue = function(){
var id = $scope.Data.idval; // not working
var id = $scope.idval; // even this one
alert(id); // its undefined
$http.post(
"query.php", {
'ID': id,
}
).then(function(response) {
console.log(response.data);
});
}});

Here is a working solution for your code:
You need to declare an object and bind it to ng-model,
$scope.Data = {};
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.Data = {};
$scope.fetchvalue = function(){
var id = $scope.Data.idval; // not working
alert(id); // its undefined
}
});
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form novalidate>
<input type="text" name="idval" ng-model="Data.idval">
<button ng-click="fetchvalue()">Submit</button>
</form>
</div>
</body>
</html>
Here is a working Plunker

I understand,
see you defined id twice, first id get the value from ng-model which must be assigning ng-model value to id variable and you override id with undefined variable called idval.
You can either remove line var id = $scope.idval; or
modify alert(id); as alert($scope.Data.idval)

You need to declare it somewhere before you use it.
$scope.DATA = ""
var id = $scope.Data.idval;
Try this out

Related

Passing data via service not updating second controller

I am trying to use service in AngularJS and pass data from one controller to another on click of a button.
I tried and can see that service value is updated but I am unable to retrieve in the second controller, however, I can retrieve in the first Controller.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<p>Search:<input type="text" ng-model="newValue"></p>
<button ng-click="myFunc(newValue)">OK</button>
</div>
<div ng-controller="myCtrl2">
{{receivedVal}}
</div>
<script>
var app= angular.module('myApp', []);
app.controller('myCtrl', function($scope,sharedProperties) {
$scope.stringValue = sharedProperties.getString();
$scope.myFunc = function(newValue) {
sharedProperties.setString(newValue);
$scope.stringValue = sharedProperties.getString();
console.log($scope.stringValue);
//I am getting the value here by calling sharedProperties.getString();
};
});
app.controller('myCtrl2', function($scope,sharedProperties) {
$scope.receivedVal = sharedProperties.getString();
console.log($scope.receivedVal);
//But I am not getting the updated value here by calling sharedProperties.getString();
});
app.service('sharedProperties', function() {
var stringValue = 'firstoccurence';
return {
getString: function() {
return stringValue;
},
setString: function(value) {
stringValue = value;
},
}
});
</script>
</body>
</html>
receivedVal is always coming blank even service is getting updated.
By looking at your HTML code; I can see both the controllers have already been instantiated.
So when you do $scope.receivedVal = sharedProperties.getString(); in controller 2, you are just getting value from service one time only (Note : You are not continuously observing the value from service). And hence in template of controller 2 the default value firstoccurence shall be displayed.
You are actually updating the value on click of OK button, which in turns updates value in service. But there is no way you told angular that now as values has been changed then now controller 2 should get this new value.
To active the scenario that you want , you need to use $broadcast and $on so that you can continuously observe change happening in controller 1.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<p>Search:<input type="text" ng-model="newValue"></p>
<button ng-click="myFunc(newValue)">OK</button>
</div>
<div ng-controller="myCtrl2">
{{receivedVal}}
<button ng-click="thisWillGetValFromService()" >update this scope's value</button>
</div>
<script>
var app= angular.module('myApp', []);
app.controller('myCtrl', function($rootScope,$scope,sharedProperties) {
$scope.stringValue = sharedProperties.getString();
$scope.myFunc = function(newValue) {
sharedProperties.setString(newValue);
$scope.stringValue = sharedProperties.getString();
console.log($scope.stringValue);
//I am getting the value here by calling sharedProperties.getString();
$rootScope.$broadcast('greeting', newValue);
};
});
app.controller('myCtrl2', function($scope,sharedProperties) {
$scope.receivedVal = sharedProperties.getString();
console.log($scope.receivedVal);
//But I am not getting the updated value here by calling sharedProperties.getString();
$scope.$on('greeting', function(ev,val){
$scope.receivedVal = val
})
});
app.service('sharedProperties', function() {
var stringValue = 'firstoccurence';
return {
getString: function() {
return stringValue;
},
setString: function(value) {
stringValue = value;
},
}
});
</script>
</body>
Above snippet shall solve your problem.
Updated :
Consider a scenario where you have routing configuration defined. So by default only controller 1 and its templates loads in HTML. Then you update ur input box and click OK button. This will save data to service.
Then later on consider on click of some link you re redirecting the app to route of your controller 2 so at this point your controller 2 will get instantiated and $scope.receivedVal = sharedProperties.getString(); this will give you updated value.
Its just a matter of when you load your template (controller) In your case you load both the controllers at a time so you need to use broadcast and on. But if your second component going to load sometime later then you can always use service.
Value is updating in the second controller
But it is not reflecting in the :
<div ng-controller="myCtrl2">
{{receivedVal}}
</div>
Because ng-controller creates new scope
you should write one extra method like in this:
https://codepen.io/amar9312/pen/yRJKGj

Values are not showing in a form input AngularJs

Console screenshot I'm having a problem with my code; I'm getting values upon clicking the button, and the same values are also showing in the console. However, I can't see the same values in the input field. Can anyone help with this?
$scope.getFees = function (id) {
getClients.getFeesPoints(id).then(function(response) {
$scope.fees = response.data.fees;
console.log($scope.fees);
});
};
<input type="text" ng-model="fees" class="mdltb-inp fee-inp"
name="fees" placeholder="35$" >
Check link of image 30 is the value of response data
Remove value="{{User}}" from the code and verify $scope.fees = response.data; binds a text value and not an object.
In case if the response.data is an object, that won't bind to an input text field. Find out the appropriate key from response.data object and bind input with that key. Also if the value is not binded still try to call $scope.$apply() after assigning the value
I this you should try this way
var app = angular.module("myapp", []);
app.controller("myCtrl", ['$scope', function($scope) {
$scope.fees="new";
$scope.getFees = function (id) {
//getClients.getFeesPoints(id).then(function(response)
//{
$scope.fees = 50;
console.log($scope.fees);
//});
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
<div ng-controller="myCtrl">
<input type="text" class="form-control" id="inputValue" name="uservalue" ng-model="fees" ng-required="true" autofocus="true" ng-blur="checkIfValid()"/>
<button ng-click="getFees(true)">Demo</button>
<h1>{{fees}}</h1>
</div>
</div>
I have Solved this by using $rootScope i.e. "$rootScope” is a parent object of all “$scope” angular objects created in a web page.

AngularJS - two way binding not working using service

I am learning Angular using W3Schools.
I just modified an example about "Services"... The following is the code:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p><input type="text" ng-model="num"></p>
<h2>{{num}}</h2>
<h1>{{hex}}</h1>
</div>
<p>A custom service whith a method that converts a given number into a hexadecimal number.</p>
<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.num = 200;
$scope.hex = hexafy.myFunc($scope.num);
});
</script>
</body>
</html>
When I update the textbox, the "HEX" part is not updating. Why?
Your hexafy.myFunc is called only once when the controller is initialized, hence only the initial value is converted to hex. If you want a function to be called on the value change of a scope variable in runtime, you need filters. AngularJS has a lot of inbuilt filters that are ready to use.
You can also define a custom filter, just like you define services or controllers.
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p><input type="text" ng-model="num"></p>
<h2>{{num}}</h2>
<h1>{{num | hexafy}}</h1>
</div>
<p>A custom filter that converts a given number into a hexadecimal number.</p>
<script>
var app = angular.module('myApp', []);
app.filter('hexafy', function() {
return function (x) {
return Number(x).toString(16); // Also convert the string to number before calling toString.
}
});
app.controller('myCtrl', function($scope) {
$scope.num = 200;
//$scope.hex = hexafy.myFunc($scope.num);
});
</script>
</body>
</html>
Further reading: AngularJS Filters
NOTE: A filter is a good idea if you're gonna be using the hexafy functionality at multiple places in/across views. Otherwise, it is just an overkill and the $scope.$watch method will work fine for you, as described in other answers
$scope.hex is not updating because there're no way for it update itself.
The hexafy.myFunc is called only once when the controller is loaded for the first time.
If you want want the $scope.hex property to change with num, you might need a watch on the num property.
$scope.$watch('num', function(newVal, oldVal) {
$scope.hex = hexafy.myFunc($scope.num); /// or newVal
}
The function passed in $scope.$watch will be called everytime the value of $scope.num changes.
for more info see https://docs.angularjs.org/api/ng/type/$rootScope.Scope (the watch section)
Hope it helps.
No need of a service here, you can simple use $watch on the num. See below code snippet, it will update your ui, I have updated your controller code, please check.
app.controller('myCtrl', function($scope, hexafy) {
$scope.num = 200;
$scope.hex = "some default val";
$scope.$watch('num', function(newValue, oldValue) {
$scope.hex = newValue.toString();
});
});
Your Text box is only bind to 'num'. '$scope.hex is not binded to your text box'. So that it is not update when you typing text. You could use '$watch' on 'num'. Read here
app.controller('myCtrl', function($scope, hexafy) {
$scope.num = 200;
$scope.$watch('num', function() {
$scope.hex = hexafy.myFunc(parseInt($scope.num));
});
});

Angular - binding a dynamically created object

I'm using Angular and I can't edit a dynamically created object, even though it is presented correctly (meaning the binding works).
I have the following view:
<html>
<head>
</head>
<body ng-app='TestApp'>
<div ng-controller='TestCtrl'>
<input ng-model="newModel().name"/>
</div>
</body>
</html>
And the following controller implementation:
var TestApp = angular.module("TestApp", []);
function TestCtrl($scope) {
$scope.newModel = function(){
return { name: 'Fresh' }
}
}
I'm using a method to return the correct object for binding because I need to execute some logic to decide which object should be binded.
The input field displays the correct, dynamically created, value. But I cant seem to edit it.
What am I doing wrong? Is this the wrong way to achieve such a functionality?
Thanks.
Instead of returning an object and by attaching a function to the scope, you can update a scope variable in the function.
Controller code:
var TestApp = angular.module("TestApp", []);
function TestCtrl($scope) {
$scope.newModel = {}; // initialize the scope variable
function updateScope () {
// do some logic
$scope.newModel = { name: 'Fresh' }; // update it with the required object
}
updateScope(); // run the function
}
HTML code:
<body ng-app='TestApp'>
<div ng-controller='TestCtrl'>
<!-- remove `()` since `newModel` is no longer a function -->
<input ng-model="newModel.name"/>
</div>
</body>
Hope this solves the issue.

How to send data from one controller to other in angularjs

How to send the json data from FirstCtrl to secondCtrl using angularjs.
Can anyone please help me out regarding this ...
First.js:
angular.module('myApp')
.controller('FirstCtrl', function ($scope) {
//firstCtrl json data
$.getJSON("sample.json", function (json) {
console.log(json);
});
});
Second.js:
angular.module('myApp')
.controller('secondCtrl', function ($scope) {
//get the firstCtrl json data here
});
I would also suggest a service that gets and returns data from and to the controllers.
we create the two controllers and then we create a service with two functions:
1. one to get the json data
2. one to return the json data
Like so:
'use strict';
angular.module('myApp', [])
.controller('FirstCtrl', function( $scope, myService ){
//we create or get the json object
$scope.myjsonObj = {
'animal':'cat',
'feed':'frieskies',
'color':'white',
'sex':'male'
};
//pass the json object to the service
myService.setJson($scope.myjsonObj);
})
.controller('SecondCtrl', function( $scope, myService ){
//call service getJson() function to get the data
$scope.myreturnedData = myService.getJson();
})
.factory('myService', function(){
var myjsonObj = null;//the object to hold our data
return {
getJson:function(){
return myjsonObj;
},
setJson:function(value){
myjsonObj = value;
}
}
});
and the HTML partial would be:
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
{{myjsonObj}}
</div>
<hr>
<div ng-controller="SecondCtrl">
{{myreturnedData.animal}}
{{myreturnedData.feed}}
{{myreturnedData.color}}
{{myreturnedData.sex}}
</div>
Hope helps, good luck.
If the second controller is nested you can use $parent to access the scope of the first controller. You would need to assign the value of json to $scope such as
$scope.json = my_json
Then in the second controller you can say
$scope.json = $scope.$parent.json;
var app = angular.module('myApp', []);
app.controller('Ctrl1', function ($scope, $rootScope) {
$scope.msg = 'World';
$rootScope.name = 'AngularJS';
});
app.controller('Ctrl2', function ($scope, $rootScope) {
$scope.msg = 'Dot Net Tricks';
$scope.myName = $rootScope.name;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!doctype html>
<html>
<body ng-app="myApp">
<div ng-controller="Ctrl1" style="border:2px solid blue; padding:5px">
Hello {{msg}}!
<br />
Hello {{name}}!
(rootScope)
</div>
<br />
<div ng-controller="Ctrl2" style="border:2px solid green; padding:5px">
Hello {{msg}}!
<br />
Hey {{myName}}!
<br />
Hi {{name}}! (rootScope)
</div>
</body>
</html>
Yo can simply make a new service with two functions one to save the date and one to give them, this service then can be accessed from any where.
In addition, you can assign the data to a $rootScope.someVar for example, and in this way too you can retrieve the data from any where
Just use $rootScope to achieve this.
In your first controller assign $rootScope.json = $scope.json; and It will available on the entire application. So, you can access $rootScope.json wherever you want on that particular app

Resources