In my angularjs project I need to go back and forth using both ng-src and src attributes in my tags.
Some images are static assets and will never change (they may be conditionally displayed) while other images are dynamic and dependent on scope variables.
May I use the mix of ng-src and src whenever I see fit?
I'm asking that because I once read that I should always use ng-src when working with angularjs, but I'm also afraid that I'm going to create bindings and watches that are really not necessary...
always using ng-src ?
I don't see any reason using ng-src without interpolation.
#Vojta Jína says: "watching attributes only makes sense, if you interpolate them"
The documentation says: "Using Angular markup like {{hash}} in a src attribute doesn't work right"
It not says using src in angular.js is not right...!
Same case with ng-href.
using ng-src without interpolation will probably not cause performance issues.
If you hit performance I guess ng-repeat is guilty.
does ng-src always creates bindings?
Actually the source code is pretty straightforward
https://github.com/angular/angular.js/blob/v1.2.7/src/ng/directive/booleanAttrs.js
ng-src will always $observe your attributes.
// ng-src, ng-srcset, ng-href are interpolated
forEach(['src', 'srcset', 'href'], function(attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 99, // it needs to run after the attributes are interpolated
link: function(scope, element, attr) {
attr.$observe(normalized, function(value) {
if (!value)
return;
attr.$set(attrName, value);
// on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
// then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
// to set the property as well to achieve the desired effect.
// we use attr[attrName] value since $set can sanitize the url.
if (msie) element.prop(attrName, attr[attrName]);
});
}
};
};
});
As for $observe, from the documantation:
The observer function will be invoked once during the next $digest
following compilation. The observer is then invoked whenever the
interpolated value changes.
Or more Simple, if there is no interpolation there is no dirty checking.
AFAIK, all performance issues angular.js has with (lots of) bindings is when it does dirty checking.
Looking further inside compile.js:
// no one registered attribute interpolation function, so lets call it manually
If there is no interpolation we end up invoking the callback only once.
In the case of ng-src you can see above the callback that $observe registers.
If there is an interpolation then angular will register a $watch (dirty checking) like so $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
Conclusion
use src when there is no interpolation
use ng-src when there is an interpolation
using ng-src without interpolation will end up running the callback only once. means it has subtle impact to performance.
Another issue is that images will not start loading until angular is bootstraped or in case you use routes (who's not?) until your views are compiled. This could a have a significant impact on load times.
Related
I'm wondering if there is any way I can get the original {{expression}} after angular has complied the directives and interpolated the expressions. For instance if there is a text e.g. Hi, Filip and the user clicks on it, I want to be able to show a pop-up with Hi, {{name}}.
Now, one way I thought of doing that is by analysing the DOM before angular (e.g. during run) and then saving the expressions as additional attributes to the parent element. However, I run into various problems with that (e.g. if parent has other child elements and they are removed, e.g. with ng-if, then I can't reliably know which expression belongs to which text node).
Since Angular keeps watchers for these expressions, it must have a reference to the text nodes they are applied on. Is there any way I could access those?
The second question is, can I somehow get the original element of ng-repeat (before it was compiled and transcluded), for the similar purpose (allowing the user to modify it on-the-fly).
I want to avoid introducing new directives as this is meant to work on existing angular applications.
I'm not concerned about performance or security (i.e. this is not for production applications but rather for prototyping/debugging).
Use factories to supply to your html expressions with reusable logic. Assumes you're using controller as syntax so you can the controller's scope as this in your view.
// factory
function() {
return 'bob';
}];
// in your controller
['somefactory', function(factory) {
this.factoryString = factory.toString(); // => "function() { return 'bob'; }"
this.factory = factory;
}];
// view
<div>hi {{this.factory()}} you were made with {{this.factoryString}}</div>
// interpolated
<div>hi bob, you were made with function() { return 'bob' }</div>
I didn't test any of that though.
From my understanding $attr.$observe fires once. So there are times to use $watch on an attribute. I am looking to unit test a directive that requires ngModel
scope.$watch(attr.ngModel, function (newValue) {
minlength = parseInt(attr.minLength);
scope.minLengthValidator(newValue);
});
Since this is using scope in the Link function it seems like I could call $digest.
My mocked attribute starts like so...
html = angular.element("<input ng-model=\"myUnit\" min-length=\"3\">");
I am not sure if I can just redefine element.attr('min-length') inside of my spec and run a $digest or if there is a more complex approach since the the watch is passing a new value.
the rest of my mock set up is like so
$rootScope = $rootScope.$new();
element = $compile(html)($rootScope);
$rootScope.$digest(element);
controller = element.controller('ngModel');
scope = element.scope();
I have not tested a $watch on a attribute before so any direction that points me towards solving this would be much appreciated.
scope.$watch(attr.ngModel, ...) will create a watcher on myUnit scope property. Once the watcher is created, it isn't bound to ngModel attribute value.
It can be tested as any other scope watcher:
scope.myUnit = ...;
$rootScope.$digest();
expect(scope.minLengthValidator).toHaveBeenCalledWith(...);
From my understanding $attr.$observe fires once.
No, $attrs.$observe observer will fire on each attribute change, it is preferable to $scope.$watch. As the manual states,
Use $observe to observe the value changes of attributes that contain
interpolation (e.g. src="{{bar}}"). Not only is this very efficient
but it's also the only way to easily get the actual value because
during the linking phase the interpolation hasn't been evaluated yet
and so the value is at this time set to undefined.
The problem is that attributes belong to DOM and can't be tested cleanly. For controller specs $attrs local dependency can be mocked, but it isn't possible in directive specs. For testability reasons it is preferable to bind attributes to scope properties and test the scope only with no $attrs involved.
I already know that you can use attr.$observe within a directive to watch the attributes if they change.
Is there an equivalent to watch the text within an element?
<div my-directive ng-bind="myText || 'Watch me!!!'">Watch me!!!</div>
In the above example, I'd want to watch the text "Watch me!!!". I'd much prefer to do this rather than $watch what is being bound to the directive because of scoping issues.
Watching the DOM for changes is EXPENSIVE, also there is no built in way within Angular to do so. Watching the scope for changes is the correct way to do this.
If you are having issues with scoping then perhaps, with more I formation,that is something we could help with as well.
It's possible to watch DOM changes, here's an example:
http://jsfiddle.net/kihu/t7zr71ma/5/
The trick is to pass a function returning anything you want to watch, e.g.:
scope.$watch(function () {
return element.text();
}, handleChange)
But I think #Enzey is right, you should avoid watching the DOM, instead you should bind data from angular scope and watch it.
I have this part of code inside ng-repeat:
<div ng-show="parameter == 'MyTESTtext'">{{parameter}}</div>
where parameter is some $scope string variable ...
I wanted to see if its possible to check (inside ng-show for instance) whether parameter contains a substring.
You could do this with:
<div ng-show="parameter.indexOf('TEST') != -1">{{parameter}}</div>
which seems to be working; it displays every parameter that contains 'TEST' keyword.
I was wondering:
is this a correct way of doing this within AngularJS app?
Is it OK to use javascript built in functions like that?
EDIT:
parameter is actually formed like this: (and is thus not a $scope variable as I said above, sorry)
<div ng-repeat="(parameter,value) in oneOfMyScopeArrays">
UPDATE
Since you're dealing with strings in ngRepeat and not objects, there's no place to set flag to in your data elements. In this case I would advise using a custom directive. I do not agree with Darryl Snow's opinion that directive in this case is redundant. With directive (as it was the case with flag in controller) you can evaluate parameter once instead of doing so in every $digest cycle. Furthermore, if you decide to implement same functionality in other template, instead of copying the expression around, which is redundant, you'd reuse same directive. Here's a quick idea of such directive:
.directive('parameter', function() {
return {
link: function($scope, $element, $attrs) {
$attrs.$observe('parameter', function(parameter) {
if (parameter.indexOf('TEST') == -1) {
$element.hide();
} else {
$element.text(parameter);
$element.show();
}
});
}
}
});
Template:
<div parameter="{{parameter}}"></div>
This directive even sets up one watcher less per parameter comparing to your original solution, which is better performance wise. On the other hand, it disables two-way binding (parameter text is rendered once), so it won't work in case you want to edit parameter string in place.
ORIGINAL ANSWER
Is it correct way? Technically yes, because it works. Is it OK? Not so much because of several reasons:
Performance. Everytime $digest loop runs (it might run quite a lot, depending on interactivity of application), it has to process every such expression. Therefore string parameter.indexOf('TEST') != -1 has to be parsed and evaluated, which means calling .indexOf up to several times after each interaction, for example click on element with ngClick directive. Wouldn't it be more performant to test this assumption parameter.indexOf('TEST') != -1 once in Controller and set a flag, e.g.
$scope.showParameter = parameter.indexOf('TEST') != -1
In template you would write
<div ng-show="showParameter">{{parameter}}</div>
Model logic in template. It's hard to tell the actual reasoning from your example when the parameter should be visible, but is it up to the template to have this logic? I think this belongs to controller, if not model to decide, that your view layer would be decoupled from making assumptions about how the model actually works.
Yes, perfectly ok I think. You could write a separate directive of your own that does the same thing - it may look a bit tidier but it's ultimately redundant when angular comes with ng-show already built in, and it means a slight additional payload to the user. You could also do a $scope.$watch on parameter and set another scope variable for ng-show, but that just moves the mess from your view to your controller.
$scope.$watch('parameter', function(){
if(parameter.indexOf('TEST') != -1)
$scope.showit = true;
});
and then in the view:
<div ng-show="showit">{{parameter}}</div>
According to the documentation a template can be a function which takes two parameters, an element and attributes and returns a string value representing the template. It replaces the current element with the contents of the HTML. The replacement process migrates all of the attributes and classes from the old element to the new one.
The compile function deals with transforming the template DOM. It takes three parameters, an element, attributes and transclude function. The transclude parameter has been deprecated. It returns a link function.
It appears that a template and a compile functions are very similar and can achieve the same goal. The template function defines a template and compile function modifies the template DOM. However, it can be done in the template function itself. I can't see why modify the template DOM outside the template function. And vice-versa if the DOM can be modified in the compile function then what's the need for a template function?
The compilation function can be used to change the DOM before the resulting template function is bound to the scope.
Consider the following example:
<div my-directive></div>
You can use the compile function to change the template DOM like this:
app.directive('myDirective', function(){
return {
// Compile function acts on template DOM
// This happens before it is bound to the scope, so that is why no scope
// is injected
compile: function(tElem, tAttrs){
// This will change the markup before it is passed to the link function
// and the "another-directive" directive will also be processed by Angular
tElem.append('<div another-directive></div>');
// Link function acts on instance, not on template and is passed the scope
// to generate a dynamic view
return function(scope, iElem, iAttrs){
// When trying to add the same markup here, Angular will no longer
// process the "another-directive" directive since the compilation is
// already done and we're merely linking with the scope here
iElem.append('<div another-directive></div>');
}
}
}
});
So you can use the compile function to change the template DOM to whatever you like if your directive requires it.
In most cases tElem and iElem will be the same DOM element, but sometimes it can be different if a directive clones the template to stamp out multiple copies (cf. ngRepeat).
Behind the scenes, Angular uses a 2-way rendering process (compile + link) to stamp out copies of a compiled piece of DOM, to prevent Angular from having to process (= parse directives) the same DOM over and over again for each instance in case the directive stamps out multiple clones resulting in much better performance.
Hope that helps!
ADDED AFTER COMMENT:
The difference between a template and compile function:
Template function
{
template: function(tElem, tAttrs){
// Generate string content that will be used by the template
// function to replace the innerHTML with or replace the
// complete markup with in case of 'replace:true'
return 'string to use as template';
}
}
Compile function
{
compile: function(tElem, tAttrs){
// Manipulate DOM of the element yourself
// and return linking function
return linkFn(){};
}
}
The template function is called before the compile function is called.
Although they can perform almost identical stuff and share the same 'signature', the key difference is that the return value of the template function will replace the content of the directive (or the complete directive markup if replace: true), while a compile function is expected to change the DOM programmatically and return a link function (or object with pre and post link function).
In that sense you can think of the template function as some kind of convenience function for not having to use the compile function if you simply need to replace the content with a string value.
Hope that helps!
One of the best uses of the template function is to conditionally generate a template. This allows you to automate the creation of a template based on an attribute or any other condition.
I have seen some very large templates that use ng-if to hide sections of the template. But instead of placing everything into the template and using ng-if, which can cause excessive binding, you can remove sections of the DOM from the output of the template function that will never be used.
Let's say you have a directive that will include either sub-directive item-first or item-second. And the sub-directive will not ever change for the life of the outer directive. You can adjust the output of the template, prior to the compile function being called.
<my-item data-type="first"></my-item>
<my-item data-type="second"></my-item>
And the template string for these would be:
<div>
<item-first></item-first>
</div>
and
<div>
<item-second></item-second>
</div>
I agree that this is an extreme simplification, But I have some very complicated directives and the outer directive needs to display one of, about, 20 different inner directives based on a type. Instead of using transclude, I can set the type on the outer directive and have the template function generate the correct template with the correct inner directive.
That correctly formatted template string is then passed on to the compile function, etc.