I have started learning angular.js but I am kind of having trouble understanding the data binding and scopes.
Here is my Html file :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"> </script>
<title>Egghead</title>
</head>
<body data-ng-app="myApp">
1. <div>
NAME : <input type = "text" name = "name" data-ng-model="data.name"/>
Typed Name : <b>{{data.name}}</b>
<br><br>
EMAIL: <input type = "email" name = "email" data-ng-model="data.email"/>
Typed Email : <b>{{data.email}}</b>
</div>
2. <div data-ng-controller="firstController">
NAME : <input type = "text" name = "name" data-ng-model="data.name"/>
Typed Name : <b>{{data.name}}</b>
<br><br>
EMAIL: <input type = "email" name = "email" data-ng-model="data.email"/>
Typed Email : <b>{{data.email}}</b>
</div>
3. <div data-ng-controller="secondController">
NAME : <input type = "text" name = "name" data-ng-model="data.name"/>
Typed Name : <b>{{data.name}}</b>
<br><br>
EMAIL: <input type = "email" name = "email" data-ng-model="data.email"/>
Typed Email : <b>{{data.email}}</b>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
Now when I have this module for my current html :
(function(){
var myApp = angular.module('myApp', []);
myApp.controller('firstController', function($scope, $rootScope) {
/*$rootScope.data = {name : "root", email : "root#gmail.com"};
$scope.data = {name : "Ishan", email : "soni.ishan.nitj#gmail.com"};*/
});
myApp.controller('secondController', function($scope) {
/*$scope.data = {name : "Divyan", email : "soni.divyan#gmail.com"};*/
});
})();
any changes that I make in any of the textbox for say the "name" input reflects and is bound everywhere. Example I make a change in the input text with name = "name" inside the second controller, the value in the text box for first also changes, but when I remove the comments from my javascript file, any change I make in the second controller's input box are not reflected in the first's input box. Why?
$rootScope is parent of all scopes, so if you assign property to it, it will be available everywhere in views. Every controller has $scope, you have two sibling controllers, so they have different scopes, if you want to share data between controllers, you shall use service. Like this:
myApp.factory('dataSrvc', function () {
return {
getData: function () {
return {
name : "Divyan",
email : "soni.divyan#gmail.com"
};
}
};
});
Then inject it into controllers:
myApp.controller('firstController', function($scope, dataSrvc) {
scope.data = dataSrvc.getData();
});
myApp.controller('secondController', function($scope, dataSrvc) {
scope.data = dataSrvc.getData();
});
In this case changes in first controller will not reflect on second and vice versa, because getData returns new instance of object every time (with same data).
Related
I have a dropdown in angularJS defined as:
$scope.Ids = [ {
id : 'ID-100',
name : 'ID-100'
}, {
id : 'ID-200',
name : 'ID-200'
}, {
id : 'ID-300',
name : 'ID-300'
} ];
$scope.Id = $scope.Ids[0];
<select class="custom-select" ng-model="Id" ng-options="choice.name for choice in Ids"></select>
My requirement is to dynamically populate these Ids from DB.
I have a spring controller that makes a call to DB:
$http({
'url' : '/getIds',
'method' : 'POST',
'headers' : {
'Content-Type' : 'application/json'
},
'params' : data
}).then(function(response) {
$scope.Ids = response.data.Ids;
});
and yields a list:
["ID-100", "ID-200", "ID-300"]
0: "ID-100"
1: "ID-200"
2: "ID-300"
My $scope.Ids will now be having the new list. I need to map this list to my $scope.Ids in dropdown format and make my dropdown display the first record.
Can someone give an idea on how to achieve this?
Your code is already correct, however your approach should be like below.
DEMO
var app = angular.module('todoApp', []);
app.controller("dobController", ["$scope",
function($scope) {
$scope.Ids = [{
id : 'ID-100',
name : 'ID-100'
}, {
id : 'ID-200',
name : 'ID-200'
}, {
id : 'ID-300',
name : 'ID-300'
}];
$scope.Id = $scope.Ids[0];
}]);
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<title>To Do List</title>
<link href="skeleton.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="MainViewController.js"></script>
</head>
<body ng-controller="dobController">
<select class="custom-select" ng-model="Id" ng-options="choice.name for choice in Ids"></select>
<div>
<h1> Selected one is : {{Id}} </h1>
</div>
</body>
</html>
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
I am getting json output from laravel 5.2 form request validation
My json output is:
{
"title": [
"The title field is required."
],
"description": [
"The description field is required."
],
"address.city": [
"City field is required"
]
}
Appending this output to object
var self = this;
self.error = {
address: {}
};
var onFailure = function (response) {
angular.forEach(response.data, function(value, key) {
self.error[key] = value[0];
});
};
I want to access this error object to my view, for "address.city", I can't access it using "ctrl.error.address.city", rest I can access
How to append object with key containing "." and show it in view?
Here is what you need. But its better not to have (.) in a property name. Instead you can use a underscore(_). Avoid using dot(.) as a chaaracter in property names.
var myApp = angular.module('MyApp', []);
myApp.controller('MyCtrl', function ($scope) {
$scope.foo={};
$scope.foo['hello.There'] = "I'm foo!";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyCtrl">
{{foo["hello.There"]}}<br />
<input type="text" ng-model="foo['hello.There']" />
</div>
if you know the key name then the only way you can access it is by [].
Check the fiddle for more info.
https://jsfiddle.net/9f4mbh1h/1/
You need to change your code to this
in your controller
myApp.controller('MyCtrl', function ($scope) {
$scope.foo={};
$scope.foo "hi";
});
in html
<div ng-app="MyApp" ng-controller="MyCtrl">
<input type="text" ng-model="foo" /> </div>
I have a json file of objects that store the properties to be used in a directive.
I want to use the json obj model value in the directive, but nothing I am trying is working.
Anyone have any ideas what I am doing wrong / missing? I find this very confusing.
Hope someone can help been trying this for days now!
Edit::
I have a $http service that gets and returns the Json object and I can access the properties fine.
I am specifically trying to use the value of the json obj model property -- "model" : "ticketData.contactname" as the dynamic value of the ng-model.
If I just use the ticketData.contactname obj then it works fine and I can edit the model value, but if I try and use the string from the Json obj then it just prints the string into the input box.
I do not know what to do. I am sure it is something basic I am missing.
Thanks in advance
Json sample:
[
{
"inputsContact" : [
{
"labelName" : "Contact Name",
"placeholder" : "Enter your name",
"model" : "ticketData.contactname",
"type" : "text"
}
}
]
Html sample:
<text-input-comp inputdata="contactName" ng-model="contactModel"> </text-input-comp>
Directive text-input-comp:
.directive('textInputComp', [ '$compile', function($compile){
return {
restrict: 'E',
scope: {
inputData: '=inputdata',
modelData: '=ngModel'
},
templateUrl: '/app/views/partials/components/textInputComp.html'
}
}]);
Directive template sample:
<label> {{ inputData.labelName }} </label>
<input type="text" ng-model="modelData" ng-model-options="{ getterSetter: true }" placeholder="{{ inputData.placeholder }}" />
<div ></div>
Controller sample:
$scope.contactName = $scope.inputData[0].inputsContact[0];
$scope.contactModel = $scope.inputData[0].inputsContact[0].model;
i think u need to get the json file first then do all the manupilation
have a look at this 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="customersCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("customers.json").then(function (response) {
$scope.myData = response.data.records;
});
});
</script>
</body>
</html>
What u were missing is this
Just replace the customer.json file with your json and u are good to go
and
1.$http is service responsible for communicating with other file. $http says get file from ‘js/data.json’ and if the operation is a ‘success’ then execute a function holding the ‘data’ which it got automatically from data.json file
to make u understand.
2.A one more line above: [‘$scope’, ‘$http’, function($scope, $http){ … }] is little bit tricky: it takes an array holding two objects one is $scope and other is a service i.e $http. The reason we have this in array is angularJS automatically minifies code which means it removes extra spaces and shorten variable names for faster performance but sometimes this minification causes trouble so we just told controller NOT to minify $scope, $http services and function inside array.
I have the following AngularJS code, where I loop through the object array using ngRepeat. I have a validation for the numeric field. The issue that I face is that, even if one record's validation fail, the error message is thrown for all records. I am not sure where is the issue.
JSFiddle Link - http://jsfiddle.net/jdev_hari/kduh4h5p/5/
Controller Code
var app = angular.module('myapp', [], function () {});
app.controller('AppController', function ($scope) {
$scope.scholarships = [
{
"name" : "abc",
"amount" : "456"
},
{
"name" : "def",
"amount" : "789"
}
];
});
HTML Code
<div ng-repeat="scholarship in scholarships">
{{scholarship.name}}
<input type="text" id="sAmount-{{$index}}" max="500" ng-model="scholarship.amount" required/>
<div ng-show="scholarship-{{$index}}.$error.max">Error</div>
</div>
Output
abc
Error
def
Error
What I fix
Use ng-form - HTML
Input type for "number" not "text" - HTML
Named input - HTML
Fix amount string to number - JS
As a comment, It may possible duplicate of How to validate inputs dynamically created using ng-repeat, ng-show (angular)
After you read that question and answers, you may understand my answer.
HTML Code
<ul ng-repeat="scholarship in scholarships">
<ng-form name="myForm">
{{scholarship.name}}
<input type="number" name="scholarshipName" id="sAmount-{{$index}}" max="500" ng-model="scholarship.amount" style="width:100px;" required integer />
<div class="alert error" ng-show="myForm.scholarshipName.$error.max">max error</div>
</ng-form>
</ul>
JS Code
var app = angular.module('myapp', [], function () {});
app.controller('AppController', function ($scope) {
$scope.scholarships = [
{
"name" : "abc",
"amount" : 456
},
{
"name" : "def",
"amount" : "789"
}
];
});