How same variable is used for ng-bind and ng-model - javascript

I am exploring AngularJS1 and found something strange, please help me to find how name is working for both ng-bind and ng-model here.
Output is coming as :John Doe but it is working for same variable name with bind and model there it is confusing me.Please help me to understand.
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="name">
<h1>{{name}}</h1><br>
<p ng-bind="name"></p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
</script>

They are all the same variable. You have $scope.name and you're telling ng-bind and ng-model to use $scope.name;
ng-model="name" <-- Angular looks on the scope object for a property called name. If it's there it uses it, if it's not, it'll create it.
ng-bind="name" <-- Angular looks on the scope for a property called name. Then uses that value.
Angular created a scope object for the div with ng-controller
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="name">
<h1>{{name}}</h1><br>
<p ng-bind="name"></p>
</div>
All directives with-in that div's hierarchy can access the scope object.
If you Google "Understanding Angular scopes" or something similar you'll get a lot of articles on it.
http://blog.carbonfive.com/2014/02/11/angularjs-scopes-an-introduction/

Related

Angularjs - Loading JSON data with $scope values (dynamic) returns undefined

I have ng-model to my input field like below.
<div ng-app="myApp" ng-controller="GlobalCtrl">
<input type="text" ng-model="FirstName">
{{FirstName}}
</div>
Now in my controller console.log $scope.FirstName is the correct values I give in my view.
But when I try to load the $scope into a JSON like structure I get undefined.
myApp.controller('GlobalCtrl', function($scope) {
$scope.loadedata = {"asd":$scope.FirstName};
console.log($scope.FirstName); //this is fine
console.log($scope.loadedata); //but this is undefined.
});
Now $scope.loadedata) is undefined. why is it? what am I doing wrong?
There are a few things about your code snippet. You are using an input bar where your DOM is trying to render FirstName which is undefined. See this demo for the proper us of the input and two-way binding template-controller relationship.
https://material.angularjs.org/latest/demo/input
Also, where are you calling the console.log()? I assume after the controller call?
My view:
<div ng-app="myApp" ng-controller="GlobalCtrl">
<input type="text" ng-model="req.FirstName">
{{req.FirstName}}
</div>
My Controller :
myApp.controller('GlobalCtrl', function($scope) {
$scope.req = {};
console.log(JSON.stringify($scope.req));
});
After a long research, I found out that it's better to do without serializing and you can do like this using ng-model. And it works.

How to use ng-bind on a td tag?

I have the following <td> element
<td translate="Price-{{product-op}} {{product-np}}" translate-values=GetVal()></td>
Now, GetVal() function is potentially dangerous because it is in a third party app.
So, I have decided to strip off any malicious elements. Decided to use ng-bind
The problem is how to ng-bind and then translate in the above code?
I came up with something like,
<td ng-bind translate="Price-{{product-op}} {{product-np}}" translate-values=GetVal()></td>
but it throws angular exception.
Any ideas ?
If you are using the Angular Translate library (https://angular-translate.github.io), the translate directive should bind the value automatically. If you remove the ng-bind, it should work.
But I am not sure what library you are using for your translations, so my suggestion might not help you. You might have to provide more information.
Also ng-bind requires a value in the $scope - for example put $scope.myValue = 'My Value' in your controller and then use this in your HTML <td ng-bind="myValue"></td>. But again, I do not know what the translate directive is supposed to do.
I don't understood exactly what do you want to do, But I imagine that the exception is because the 'ng-bind' prop needs a value to do a bind like this:
<script>
angular.module('bindExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.name = 'Whirled';
}]);
</script>
<div ng-controller="ExampleController">
<label>Enter name: <input type="text" ng-model="name"></label><br>
Hello <span ng-bind="name"></span>!
</div>

accessing global variables in angular scope

In http://www.w3schools.com/angular/tryit.asp?filename=try_ng_repeat_object
instead of
<div ng-app="" ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">
Is there a syntax to refer to an external variable declared elsewhere in ng-init (and NOT declared in angularjs controller) as this one doesn't work:
<script>
var myNames = [
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]
</script>
<div ng-app="" ng-init="names=myNames">
I know it's bad practice but I use another framework also and don't want to duplicate the content of the variable. And it's just for prototyping not code for real app.
Or else if I use ng-init initial declaration, can I refer it from another script variable ?
It will not work because of the following reasons
Script tag is for to the html document's javascript. It has no relationship with angular's ng-init directive.
The angular documentation about ngInit directive warns as shown below.
Best practise is to go with controllers when these kind of situations arises.
Updated as per the discussion in chat
<body>
<script>
var myNames = [
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}];
var app = angular.module('myApp',[]);
app.controller('myController',function($scope){
$scope.names=window.myNames;
});
</script>
<div ng-app="myApp" ng-controller="myController">
<p>Looping with objects:</p>
<ul>
<li ng-repeat="x in names">{{ x.name + ', ' + x.country }}</li>
</ul>
</div>
</body>

ng-controller variable Vs ng-init vairable

For below code, using angularJS,
<script type="text/javascript">
angular.module('app').controller('add', ['$scope',function($scope) {
$scope.name = "Bonita Ln";
}]);
</script>
corresponding Javascript code to access $scope variable member name is,
<div ng-app="app" ng-controller="add">
<script type="text/javascript">
var dom_el = document.querySelector('[ng-controller="add"]');
var ng_el = angular.element(dom_el);
var ng_el_scope = ng_el.scope();
var name = ng_el_scope.name;
</script>
</div>
Below is the angular code, accessing ng-init variable name using angular expression,
<body ng-app="">
<div ng-init="name='Bonita Ln'">
{{name}}
</div>
</body>
How do I access the ng-init variable name using JavaScript?
you can do this by accessing variable $scope.name in your controller, but it has to be define inside your scope.
<div ng-init="name='Bonita Ln'">
{{name}}
<div ng-controller="MyCtrl">
Hello, {{name2}}!
</div>
</div>
angular.module('myApp',[]).controller('MyCtrl',function($scope) {
$scope.name2 = $scope.name;
})
this works, as you have define name in parent scope to controller, and is being inherited
but if for same controller html template will look like that:
<div ng-controller="MyCtrl">
<div ng-init="name='Bonita Ln'">
{{name}}
Hello, {{name2}}!
</div>
</div>
then it won't work, as variable was undefined when controller function was invoked
You could use it in exactly the same way, but you shouldn't.
I've downvoted your question because it is really really really bad practice, and I mean like every line of code you provided is bad practice.
I'm struggling trying to find out what you'd like to do, so I can't really provide you with better code to do so, but I can provide you with some links you must check out before continuing with whatever you're coding now.
Shaping up with Angular is a free codeschool course provided by the angular team, it is a really good course that will give you more insight on how to use angular than the phone-tutorial on the angular website.
Papa Johns Angular styleguide a great guide on how to write maintainable code.
thinkster.io a step by step guide to learn to master Angular
egghead.io a collection of good video tutorials
I know that my comment sounds quite harsh, but future you will thank you if you write more standardized Angular, and keep to a defined style-guide.
Also remember, in angular, your code should not know about the DOM, you don't need to specify eventListeners to DOM-elements, just use the appropriate directives like ng-click.
(yes I am aware that there can be exceptions to the rule)

AngularJS ng-model $scope in ng-repeat is undefined if update from outside ng-repeat $scope is also undefined

I was looking this example AngularJS ng-model $scope in ng-repeat is undefined in this question first answered by #Gloopy here http://jsfiddle.net/VnQqH/128/
My question is can I update ng-model values in ng-repeat scope from outside of ng-repeat scope like this:
<div ng-app="MyApp">
<div ng-controller="PostCtrl">
<div ng-repeat="post in posts">
<strong>{{post}}</strong>
<input type="text" ng-model="postText">
</div>
/*Update ng-model values (in ng-repeat scope) using single click*/
save post
</div>
</div>
Here is controller:
angular.module('MyApp',[]);
function PostCtrl($scope) {
$scope.posts = ['tech', 'news', 'sports', 'health'];
$scope.savePost = function(post){
alert( 'post stuff in textbox: ' + post);
}
}
I tried but got undefined :( My experimental fiddle is here http://jsfiddle.net/hot81o2z/ If anyone has the solution for this problem please share. Many thanks in advance.
You can make use of $parent in order to pass a scope variable outside of the ng-repeat directive, something like this
HTML:
<div ng-app="MyApp">
<div ng-controller="PostCtrl">
<div ng-repeat="post in posts">
<strong>{{post}}</strong>
<input type="text" ng-model="$parent.postText">
</div>
<!--Update on single click-->
save post
</div>
</div>
Controller: Not changed anything, kept what you had
Working Demo

Categories