Angular.js. Two-way data binding breaks when using services - angularjs

The problem is that SecondName attribute is not updating when I input text in the field.
please look at this code at jsfiddle: http://jsfiddle.net/HEdJF/253/
HTML:
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<div>
<input type="text" ng-model="Data.FirstName"><!-- Input entered here -->
<br>FirstName is : <strong>{{Data.FirstName}}</strong><!-- Successfully updates here -->
</div>
<hr>
<div ng-controller="SecondCtrl as Second">
SecondName: {{Second.Data.SecondName}}<!-- How do I automatically updated it here? -->
</div>
</div>
</div>
JS:
var myApp = angular.module('myApp', []);
myApp.service('Data', function(){
var obj;
return obj = { FirstName: '54',
SecondName: '22',
f: function(){
obj.FirstName = '1';
obj.SecondName = obj.FirstName;
}
};
});
myApp.controller('FirstCtrl', function( $scope, Data ){
Data.f();
$scope.Data = Data;
});
myApp.controller('SecondCtrl', function( Data ){
Second = this;
Second.Data = Data;
});

It's not going to work like you think it should. This line:
obj.SecondName = obj.FirstName;
creates a new property SecondName equal by value to the FirstName. However since both properties are primitive types (String) there is no connection between them. In other words obj.SecondName does not reference obj.FirstName.
You have two options.
Option 1. (bad) Set up additional watcher on FirstName change, and once that happens update SecondName respectively
$scope.$watch('Data.FirstName', function() { Data.SecondName = Data.FirstName; });
http://jsfiddle.net/HEdJF/254/
Option 2. Don't introduce additional watchers and change your architecture. For example, use FirstName in the second controller too, since they are supposed to be equal.
http://jsfiddle.net/HEdJF/255/

This is a scoping issue because of your nested scopes. Take a look at this website for a clear explanation: http://toddmotto.com/digging-into-angulars-controller-as-syntax/. There's a few different solutions to solve your problem under the Nested Scopes section.

The problem with your code is that the First Controller is just changing the value of Data.FirstName object, hence the changes are not reflecting on your second controller because the value of SecondName does not change after it is initialized in the first controller. So you have to set your Data.SecondName
in your data as well.
Alternatively, you can do this.
<div>
<input type="text" ng-model="Data.FirstName"><!-- Input entered here -->
<br>FirstName is : <strong>{{Data.SecondName=Data.FirstName}}</strong><!-- Successfully updates here -->
</div>
You can also use directives to achieve this functionality, but I guess you are just looking for the above solution.
Cheers!

Related

ng-init does not initialize my selected model

I have a select option where I get a list of titles i.e. Mr, Mrs, Dr etc. from an API, the code looks like this in the front end:
<select class="form-control" name="titleSelect" id="titleSelect" ng-options="option.value for option in titleData.availableOptions track by option.key" ng-model="adult[$index].selectedTitle" ng-init="adult[$index].selectedTitle = titleData.availableOptions[0]"></select>
And this in the controller:
var getPassengerTitle = PassengerDetailsAndCardDetailsService.getPassengerTitle();
PassengerDetailsAndCardDetailsService is service, where I get the API data i.e. the title data. Furthermore this service returns a promise.
This is where I set the title Data:
getPassengerTitle.then(function(result){
$scope.availableTitles = angular.fromJson(result.titleList);
$scope.tempListOfTitles = [];
for(var key in $scope.availableTitles){
$scope.tempListOfTitles.push({key : key, value : $scope.availableTitles[key]});
};
$scope.titleData = {
availableOptions: $scope.tempListOfTitles,
};
});
When I try to ng-init to the first option (that is Mr.) it does not work as in a blank option is shown. However when I tried statically defining the titleData in an object it works, could you please help me?
UPDATE:
I failed to mention that the title data is inside an ng-repeat to support input for multiple people/passengers in this case. Therefore I'm using adult[$index] where it creates an ng-model for each person/passenger.
I am not sure if this is the required behavior you want, but if you want to initialise the title on selecting an option you can either use the value from ng-model or use the event handler ng-change. Here is an example jsbin which handles the change and assigns the new value to ng-model. Let me know if this is what you were looking for
try like this.
var myapp = angular.module('app', []);
myapp.controller('Main', function ($scope) {
var vm = this;
vm.adult = {
'selectedTitle':'1'
};
vm.titleData = [
{'key':'0','value':'Mr'},
{'key':'1','value':'Ms'},
{'key':'2','value':'Dr'}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app = "app">
<div ng-controller="Main as ctrl">
<div class="select-style">
<select ng-options="option.key as option.value for option in ctrl.titleData" ng-model="ctrl.adult.selectedTitle"></select>
</div>
</div>
</div>

multiple inputs based on array

My angular experience is basically about 3 days part time, so there's probably something simple I'm missing here.
I'm trying to create a dynamic list of multiple inputs based on an array, which I then want to reference from elsewhere in the app. What I've tried is loading a template from a custom directive, then $compile-ing it.
<input data-ng-repeat="term in query" data-ng-model="term">
My controller contains $scope.query = [""] which successfully creates the first empty input box. But the input box doesn't seem to update $scope.query[0] when I modify it. This means that when I try to create another empty input box with $scope.query.push(""); (from a keypress listener looking for the "/" key) I get a "duplicates not allowed" error.
I've tried manually listening to the inputs and updating scope.$query based on their value, but that doesn't feel very "angular", and results in weird behaviour.
What do I need to do to link these values. Am I along the right lines or way off?
I made a simple jsfiddle showing how to use an angular model (service) to store the data. Modifying the text inputs will also modify the model. In order to reference them somewhere else in your app, you can include TestModel in your other controllers.
http://jsfiddle.net/o63ubdnL/
html:
<body ng-app="TestApp">
<div ng-controller="TestController">
<div ng-repeat="item in queries track by $index">
<input type="text" ng-model="queries[$index]" />
</div>
<br/><br/>
<button ng-click="getVal()">Get Values</button>
</div>
</body>
javascript:
var app = angular.module('TestApp',[]);
app.controller('TestController', function($scope, TestModel)
{
$scope.queries = TestModel.get();
$scope.getVal = function()
{
console.log(TestModel.get());
alert(TestModel.get());
}
});
app.service('TestModel', function()
{
var queries = ['box1','box2','box3'];
return {
get: function()
{
return queries;
}
}
});

Get value from HTML page to angularJS file

I tried to get the HTML page value to angularJS function , The below steps are which i tried.
HTML page :
<label class="item-input item-stacked-label">
<span class="input-label cont_det_label">First Name</span>
<p class="contact_display" id="txtFirstName" ng-model="testName">Satya</p>
</label>
angularJS Page :
.controller('SocialNetworkCtrl', ['$scope','$http','$state','ContactsService','$ionicNavBarDelegate','$ionicLoading','$ionicPopup',function($scope, $http, $state, ContactsService, $ionicNavBarDelegate, $ionicLoading,$ionicPopup) {
$scope.showUserProfile = function() {
$state.go("linkedin");
var firstname = (document.getElementById("txtFirstName").value);
}
}])
So I need var firstname = Satya ?? Is it correct way please guide me to access this value .
var firstName = $scope.testName
<input ng-model="testName" />
testName is the ng-model name that you have give. It will be automatically binded to your controller. No need the get the value using document.getElementById
Wrong usage , why ng-model in <p> tag??
Update
Change your fiddle with the following code, it will work. Also make sure framework is selected properly (as in the image)
<div ng-app ng-controller="testController">
<input ng-model="testDataName" ng-change="check()" /> {{testDataName}}
After ng-change : {{checkName}}
</div>
function testController($scope) {
$scope.testDataName="Dummy Name";
$scope.check = function () {
$scope.checkName=$scope.testDataName;
console.log($scope.checkName);
};
}
its a text node, you will require .innerHTML or '.innerText', .value is for form inputs
var firstname = (document.getElementById("txtFirstName").innerHTML);
and don't use ng-model on a p element, change it to like this
<p class="contact_display" id="txtFirstName">{{testName}}</p>
just use $scope.testName to get the value, no need for firstname = (document.getElementById("txtFirstName").innerHTML); querying DOM for value is jQuery style, use angular the $scope for 2 way bindings
Read more at official doc
Update here is updated function on loginCtrl
.controller('loginCtrl', ['$scope', function ($scope) {
$scope.testNameData = 'Satya';
$scope.doLogin = function() {
alert($scope.testNameData);
};
}])
If you really want to go jQuery way here is what you can do, its not recommended, you should use angular directive to do DOM manipulation
$scope.showUserPro = function() {
$ionicLoading.show();
// Here i need the value of <p tag>
var name = document.getElementById("txtFirstName"),
firstNameFromHtmlPtag = name.innerText;
console.log(firstNameFromHtmlPtag, 'Doing API Call 1');
}

Stop two way databinding on model

I'm fairly new to Angular so if there is some incorrect thinking here, please let me know.
I'm trying to create two separate scope variables based on the same data set. I assumed that I would just be able to set them to different variables (as shown below) and it would work. I've found, however, that no matter what they are named or how they are defined (even in a directive!) that changing one changes them all.
So...what I expect/would like to see is that if I change the input in the top repeat it will only change the model for that repeat. Currently it changes all three.
Where am I going wrong here? I assume this has something to do with the two way data-binding. Thanks in advance!
Plnkr
HTML:
<h4>data</h4>
<div ng-repeat="person in data">
{{person.name}}
<input ng-model="person.name" />
</div>
{{data[0].name}}
<br>
<br>
<h4>testData</h4>
<div ng-repeat="person in testData">
{{person.name}}
<input ng-model="person.name" />
</div>
{{testData[0].name}}
<h4>Directive</h4>
<div tester data="data"></div>
Directive HTML:
<div ng-repeat="person in data">
{{person.name}}
<input ng-model="person.name" />
</div>
{{data[0].name}}
JS:
var app = angular.module('test', []);
(function () {
var testController = function ($scope) {
var data = [
{name:'Jordan', age:30},
{name:'Sean', age:32},
{name:'Seth', age:26}
];
$scope.data = data;
$scope.testData = data;
}
testController.$inject = ['$scope', '$http'];
app.controller('testController', testController);
}())
app.directive('tester', function(){
return {
restrict: 'A',
templateUrl: 'directive.html',
//If percent = true then that table should have a "percent change" th
scope:{
data: '=data'
}
}
})
I'm trying to create two separate scope variables based on the same
data set. I assumed that I would just be able to set them to different
variables (as shown below) and it would work
Actually both those javascript variables are pointing to the same data structure in memory. So when you modify this structure it reflects to both of them. Think of those data and testData variables as pointers to the same data.
You could copy this data structure in order to create 2 different instances of it in memory so that changes to one do not reflect to changes of the other:
$scope.data = data;
$scope.testData = angular.copy(data);
and if you wanted to reflect this in your directive, go ahead and clone the instance you are passing to it as well:
<div tester data="angular.copy(data)"></div>
Here both data and testData pointing to the same reference that why they are replicating same value.There are 2 solutions we can apply if there is function references, date object, and any undefined values which need to be there in the object after copy then appropriate option is $scope.testData = agular.copy(data);
Another options $scope.testData = JSON.parse(JSON.stringify(data)); but following keys won't be copyed.
functions.
Date object
properties with the value undefined

Why doesn't an input field change update angular model?

This is a very newbie question but why doesn't
document.getElementById("demo").value
update angular model? It updates the input field, but it updates the model only after manually putting something into the field.
Here's the code:
<div ng-controller="AddCtrl">
<input type="text" id="demo" ng-model="test.fld" ng-change="change()"></input>
<br />
[ pop ]
[ add ]
<p>Test-field: {{test.fld}}</p>
</div>
<script>
function somefnc() {
document.getElementById("demo").value = "hi";
}
</script>
The answer is purely related to the way angular binds data. The simplest answer would be, after manually changing the form data, $scope.$apply() must be called for the element's scope. Called outside the "Angular world" you could change somefnc to:
function somefnc() {
document.getElementById("demo").value = "hi";
$('#demo').scope().$apply();
}
Best practices say that any direct dom manipulation should happen only in directives. Ideally, you would change this value in the controller with something like:
$scope.somefnc = function(){
test.fld = "hi";
}
Anything done through the angular scope like this does not need $scope.$apply, only direct dom manipulation does.
The full example is here
<div ng-controller="AddCtrl">
<input type="text" id="demo" ng-model="test.fld" ng-change="change()"></input>
<br />
[ pop ]
[ add ]
<p>Test-field: {{test.fld}}</p>
</div>
<script>
angular.module('app').controller('AddCtrl',['$scope',function($scope){
$scope/test = {fld: ''};
$scope.add = function(){
$scope.test.fld += test.fld
}
$scope.change = function(){
alert('I changed!');
}
$scope.somefnc = function() {
$scope.test.fld = "hi";
}
}])
</script>
Because AngularJS can only watch the model change in AngularJS's scope. So you need to modify using Angular's way not other ways like jQuery if you want the 2-way data binding magically work.

Resources