How can I console.log expression in AngularJS? - javascript

As a new "Angularian", I have this:
<div data-ng-app="" data-ng-init="">
<input type="text" ng-model="hello">
<p>{{hello}}</p>
</div>
But I wonder, how can I console.log whatever I type in the expression (ng-model)?
(e.g. if I type "Soylent Green is people" in the text field I want to see it in Chrome's Inspector window)

You can use console.log($scope.hello); inside your controller.
I suggest you to take a look about Addons/Extensions like Batarang and
ng-inspector.
This is the newest one, and as the name suggests, it allows you to inspect your application's scopes.

Use ng-change directive with your input tag like
<input type="text" ng-model="hello" ng-change="textChange()" >
and in your controller
$scope.textChange = function () {
console.log($scope.hello);
}
https://jsfiddle.net/walioulislam/wpjwavrc/

You have a controller for this app, if you don't know about controllers you can read the documentation in w3schools
You can do console.log($scope.hello) inside your controller
By default each and every variable you define in HTML is inside $scope object

Related

Angular appending html with directives from within a directive

I'm trying to write a small directive that will append the validation tags and ngMessages dynamically to the input. But I'm having trouble appending the ng-message attribute to the div.
The idea is to have this,
<div validator validations="{json_data containing error messages}">
<input name='fieldName'>
</div>
Turned in to the following according to the provided JSON.
<div validator>
<input required="required"></input>
<div ng-message="fieldName" ng-if="fieldName.$dirty>
<p ng-message="required"> scope.message </p>
</div>
</div>
I've currently managed to get the ng-required appeneded using the answer to this answer. But I can't seem to append the ng-message tag using the same technique. What should be done differently to solve this issue?
The final directive should be able to generate something like this Fiddle
The current version can be found in the Fiddle here the example works as expected until 'scope' is added. But as soon as 'scope' is added, the example stops working.
Update
I've realized that this only occurse when you add a local scope. This error doesn't occure when using the global scope and accessing the variable using scope.$eval(attrs.message)

JsViews how to make data binding happen on root object as well as its nested properties?

I am experiencing odd behavior when data linking an object to a form that led me to re-question what exactly is being data bound?
Basically I have a form that creates new Companies as well as updates them. The actual creation/update is done via ajax, which is why I am using the same form for both purposes. In the case when I have to create a company, everything works as I expect. However when I have to update a company, things don't work like how I expect them to. Please have a look at the following code.
Here is my sample Form HTML:
<div id="result"></div>
<script type="text/x-jsrender" id="CompanyFormTemplate">
<form>
<input type="text" data-link="Company.Name" />
</form>
</script>
Here is my Javascript code:
var app = new CompanyFormContext();
function CompanyFormContext() {
this.Company = {
Name: ''
};
this.setCompany = function (company) {
if (company) {
$.observable(this).setProperty('Company', company);
}
};
};
$(function () {
initPage();
...
if (...) {
// we need to update company information
app.setCompany({ Name: 'Company ABC' });
}
});
function initPage() {
var template = $.templates('#CompanyFormTemplate');
template.link("#result", app);
}
Instead of the form input showing 'Company ABC', it is empty. However if I enter anything in it, then the Company.Name value does change! But while I want the input to data bind to Name property of my Company object, I also want it to be aware of any changes made to the (parent) Company object and update it's data binding to it's Name property accordingly.
So my question is how should I change the way I am writing this code so that I can achieve a data bound both on the root object as well as the property?
The issue you were having was because in your scenario, you have paths like Company.Name for which you want to data-link to changes not only of the leaf property but also to changes involving replacing objects higher up in the path (in this case the Company).
For that you need to use the syntax data-link="Company^Path".
See the section Paths: leaf changes or deep changes in this documentation topic:
http://www.jsviews.com/#observe#deep.
See also the examples such as Example: JsViews with plain objects and array in this topic: http://www.jsviews.com/#explore/objectsorvm.
Here is an update of your jsfiddle, using that syntax: https://jsfiddle.net/msd5oov9/2/.
BTW, FWIW, in your fix using {^{for}} you didn't have to use a second template - you could alternatively have written:
<form class="form-horizontal">
{^{for Company}}
...
<input type="text" data-link="Name" />
{{/for}}
</form>
To respond also to your follow-up question in your comment below, you can associate any 'block' tag with a template. Using tmpl=... on the tag means you have decided to separate what would have been the block content into a separate re-usable template. (A 'partial', if you will). The data context for that template will be the same as it would have been within the block.
So specifically, {{include}} {{if}} and {{else}} tags do not move the data context, but {{for}} and {{props}} do. With custom tags you can decide...
So in your case you could use either {^{for Company tmpl=.../}} or {{include tmpl=.../}} but in the second case your other template that you reference would use <input type="text" data-link="Company^Name" /> rather than <input type="text" data-link="Name" />.
Here are some relevant links:
http://www.jsviews.com/#samples/jsr/composition/tmpl
http://www.jsviews.com/#includetag
http://www.jsviews.com/#fortag
I discovered one way to achieve this. It might seem complex at first but it will make sense once you understand it properly.
(PS: I wish there was a sample like this. I might just blog about it.)
HTML Markup:
<script type="text/x-jsrender" id="CompanyFormTemplate">
<form>
{^{for Company tmpl="#CompanyDetailsTemplate" /}
</form>
</script>
<script type="text/x-jsrender" id="CompanyDetailsTemplate">
<input type="text" data-link="Name" />
</script>
Javascript: No changes needed from code above.
Okay so as I said, the solution might look complicated but it turns out all I really had to do was to set up data binding first on the Company object, and then to it's property objects. I wonder if there is a more elegant solution (i.e. one in which all of this can be achieved in a single template) however this solution ensures that data-binding is happening both on the parent object as well as its' properties.
I have posted a JsFiddle for this solution, so if anyone comes across this problem and wants to understand how this solution would work for their particular problem, they will be able to play with a working solution.

Angularjs ng-model is undefined

In HTML I have this line of code:
<input type="text" class="training-comment" placeholder="Enter comment" ng-model="content" data-ui-keypress="{13:'keypressCallback($event)'}">
And in controller this:
$scope.keypressCallback = function ($event) {
console.log("comment is", $scope.content);
$event.preventDefault();
};
And when I enter some text in input and press enter in console I see that $scope.content is undefined.
Why is this ?
I put together a Plunker example here using the Angular UI and basically copying the code from the question. I then took this example and added an ng-repeat to demonstrate one of the most common issues I have seen: scope issues:
<div ng-repeat="x in collections">
<input type="text" class="training-comment" placeholder="Enter comment"
ng-model="content" data-ui-keypress="{13:'keypressCallback($event)'}" />
<br /><br />
</div>
You can find this updated plunker example here. Basically whenever you use an ng-repeat or any other directive that creates a new scope your model exists in that scope - not the parent or root scope. This means that your code might be working, but it is printing out the value from the wrong scope! For more information on scopes see the angular documentation here.
To use the plunker demo, type into the first input and press the enter key, the model will be updated. But, if you type into either of the other two boxes, though, the model will either not be updated or it will be undefined (if you have never typed into the first box).
Even if this isn't the exact issue, hopefully it will still help. Best of luck!

Dynamic variable for angular ng-click attribute

I am using the following way to use $scope variable ({{func}}() in this case) as function name in ng-click.
<button type="button" ng-click="{{func}}()">Call {{func}}</button></pre>
This works in angularjs-1.2.0rc3. See working plunkr here
Any future version from > 1.2.0rc3 throw this error
What's changed? How can I use the above syntax in current angular version?
Ok first of all I do not recommend such a usage for ng-click because angularjs itself do not support this, but if you still want to use it such a way here is your solution...
<button type="button" ng-click="$eval(functionName)()">...</button>
where
$scope.f1 = function() {
...
};
//name of function as a string
$scope.functionName = "f1";
this is what your are looking for and here is your PLUNKER example...
All I did was append scope to both variables
<form name="angular" ng-controller="Ctrl">
<button type="button" ng-click="{{scope.func}}()">
Call {{func}}
</button>
<label>Status: {{scope.status}}</label>
http://jsfiddle.net/bebold/TmKLY/1/
I wouldn't advise going this route for dynamic variable change, a better choice would be to create a directive and do the binding within the template:
A great explanation can be found HERE.

Obtaining form data from within controller

I am trying to obtain form data from the Angular controller without success.
HTML:
<form>
<input type="text" id="entityName" ng-model="ent.Name">
<button class="btn" type="button" onclick="this.blur()" ng-click="$event.preventDefault(); saveData()">Save</button>
</form>`
JS Controller:
$scope.saveData = function() {
console.log($scope.ent.Name);
}
I receive error: Error: $scope.ent is undefined
always give form a name if you want angular validation to work. Shouldn't use onclick in angular app (asking for headaches and creating testing problems) ng-clcik will automatically prevent default so you don't need to add that yourself.
You probably haven't set up an object in scope for ent. If your ng-model values didn't have a dot in them you wouldn't need to register anything in scope for ng-model to work automatically creating a scope property
$scope.ent={};
This will be object that your ng-model properties will bind to. Will need to see more code if this isn't the issue

Categories