Binding text inputs to a directives attribute - javascript

I'm trying to bind a text input to an attribute within a directive, the reason being I don't want to have to introduce a controller each time I add a new directive of this type. Is this even possible or do you always have to specify a controller when using ng-model. Code example is worth a thousand words so please take a look at http://codepen.io/scottwio/pen/HKqiw . As you type in the input the amount should change.

There are two issues with your code:
scope.$watch(attrs.amount, function (v) {...}); <=>
scope.$watch('100', function (v) {...});
which is never going to change, so does not do what you want.
Since the elements attribute is never going to change, function draw(aniTime) { var amount = attrs.amount; is not so usefull.
You can fix them like this:
scope.$watch('amount', function (v) {...});
and
function draw(aniTime) {
var amount = scope.amount;
...
See, also, this short demo.
If you want to share the specified amount with the parent scope, then you need to set up a two-way data-binding and specify a property in the parent scope to bind to. E.g.:
// Parent scope
$scope.someAmount = 100;
// In HTML
<custommarc amount="someAmount" ...
// In directive
scope: {
amount: '='
...

Related

Use angularjs function return in javascript

I have a angularJS function which returns a value and would like to create an if statement in javascript. I've tried the following but so far no luck.
AngularJS:
$scope.orderTotal = function(index) {
var orderTotal = 0;
angular.forEach($localStorage.items, function(items) {
orderTotal += items.quantity;
})
return orderTotal;
};
Javascriptfile.js:
jQuery(document).ready(function() {
document.write(orderTotal());
}
or:
if (orderTotal() > 10) {
document.write(orderTotal());
}
Is it possible to do something like this and what would it look like?
RvdM - "Because adding and removing classes on divs is something I do with javascript I need to have some variables defined in angularjs available in javascript. Are there better ways to accomplish this?"
Yes, to add and remove classes on elements in AngularJS, use the ng-class directive.
From the Docs:
ngClass
The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.
-- AngularJS ng-class Directive API Reference.
You can - I'd question why, but oh well. You can use angular.element and .scope to get the current scope your function is contained in.
For example, say your above function was inside the controller MyController
<div id="controller" ng-controller="MyController"></div>
The JS you'd use is:
var scope = angular.element(document.getElementById("controller")).scope();
scope now has access to all scope methods:
var total = scope.orderTotal();
the DOM :
<div id="mycontroller" ng-controller="mycontroller"></div>
In jquery you do this and it will access that controller and call that function
var orderTotal;
$('#mycontroller').load = function(){
orderTotal = angular.element('#mycontroller').scope().orderTotal();
}
If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed
Here you go :)

Edit html text value using directives

In my app, I'm using some variable which contain a code instead of the value itself. This code matches one field of an array which items contain the code with the matching value. What I could do to display the name is a loop to find the value based on the code. But as my app has a lot of these, I would need to do it for each value.
Here is the array:
[{code: 'PN', name: 'Panasonic'}, {code: 'SN', name: 'Sony'}]
Therefore, I thought using an attribute would be much better and cleaner. I would like to put the following jade: div(json-array={{televisions}}) {{ code }} and change the displayed code with televisions[X].name. The problem is that I'm not so familiar with directives.
I tried to use the link function to catch the value (code) and the binded variable array ({{televisions}}) but I encountered two problems:
How can I modify the div value without modifying the binded variable (code)?
How do I get the array (televisions) within my directive?
I still wouldn't use a directive for that. It is a simple presentation issue and can be easily (and declaratively) handled in the view (yet the question lacks all necessary info in order to provide the most appropriate solution).
<div>{{getTelevisionName(tv.code)}}</div>
$scope.getTelevisionName = function (code) {
for (var i = 0; i < $scope.televisions.length; i++) {
var tv = $scope.televisions[i];
if (tv.code === code) return tv.name;
}
return '';
};

Knockout js: Viewmodel property not being bound

This is my fiddle. http://jsfiddle.net/aaScC/
Please check in the example, the Score property has 3.5 value but it is being displayed as 1. I know the score property is bound to dropdown value so its coming as 1. But i want 3.5 to be displayed. Please help.
var GoalsModel = function (goals) {
var self = this;
self.goals = ko.observableArray(ko.utils.arrayMap(goals, function (goal) { return new Goal(goal) }));
};
The problem is that you just make the select element invisible. You don't want the element at all. You can use bindings if or ifnot to control this.
Here is an updated example: http://jsfiddle.net/waxwing/aaScC/1/ . I wrapped the select inside a span to make it work, but you can also use virtual bindings if you don't like to change your DOM structure.

AngularJS - Input change outside directive value passed in to directive

I am a beginner to AngularJs and I cannot figure out how to retrieve data from outside a directive. I have various input being updated and I need the directive to take this data and work with it.
For example, in the code below, the first input field is hooked up to the directive and works fine, but without putting the directive attribute on the second input field, how can the data typed in that field be updated in the directive?
HTML:
<div ng-app="myDirective">
<input type="text" ng-model="test1" my-directive>
<input type="text" ng-model="test2">
</div>
Directive:
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(attrs.ngModel, function (v) {
console.log('New Value from field 1: ' + v);
//console.log('New Value from field 2: ' + ???);
});
}
};
});
I could have explained that in text, but I think it would be much better if you watch these 3 videos by john lindquist:
Isolate Scope "#"
Isolate Scope "="
Isolate Scope "&"
And summary.
They are really short (~4min each) but very simple and useful.
PS: by the way, i recommend you to watch others as well. They are all short and precise, loved them.
Since your directive does not create a new scope, the scope variable inside the directive's link method points to the outer scope containing the two inputs. So you can replace:
//console.log('New Value from field 2: ' + ???);
with
console.log('New Value from field 2: ' + scope.test2);
Make sure to enter some data in the second input when testing or it will print undefined.
Here is a working fiddle
EDIT: If you did need to use isolate scope in your directive, you could do the following in your HTML:
<input type="text" ng-model="test1" my-directive="test2">
<input type="text" ng-model="test2">
The difference here is now passing in the test2 model into the directive, and setting up a binding to it in your directive by adding the scope property:
scope: {
otherInput: '=myDirective'
// this tells the directive to bind the local variable `otherInput`
// to whatever the `my-directive` attribute value is. In this case, `test2`
},
This allows you to access passed values in your directive. You would then change your $watches as follows:
scope.$watch(attrs.ngModel, function (v) {
console.log('New Value from field 1: ' + v);
console.log('New Value from field 2: ' + scope.otherInput);
});
// notice the syntax for watching a scope variable
scope.$watch('otherInput', function (v) {
console.log('New Value from field 1: ' + scope.test1);
console.log('New Value from field 2: ' + v);
});
I've included this in my fiddle as another example, test3 and test4.
AngularJs directive lets you to use scope with different ways and do many cool things you need.You can use your scope as not inherit, inherit and isolated.If you use scope as isolated,you can pass variables and bind it wherever you want.
here are 2 cool articles with examples, which can help you
http://www.w3docs.com/snippets/angularjs/change-variable-from-outside-of-directive.html
http://www.w3docs.com/snippets/angularjs/bind-variable-inside-angularjs-directive-isolated-scope.html

Using jQuery is it possible to combine selector assignment with a change event reassignment at the same time?

var gsaForm = $("form#search"),
gsaSite = $(":input[name=site]", gsaForm).val();
$(":input[name=site]", gsaForm).on("change", function(e) {
gsaSite = $(this).val();
});
I'd really like to clean this up (looks ugly to me). There must be a way to assign gsaSite once but cover both my bases. Is it possible?
It sounds like what you want is a variable that is always equal to the value of a form input.
You're better off assigning a variable to the input, and then just use .val() whenever you need the value:
var gsaField = $(':input[name="site"]',gsaForm);
gsaField.val();
The processing time of calling .val() each time you want the value isn't large enough to bother attaching a change event to the field just to reassign a variable.

Categories

Resources