I'm building a custom directive in AngularJS that I need to be repeated a couple of times. Currently, my page looks like this:
<div my-item ng-repeat="item in items" />
And my directive looks like this:
module.directive('myItem', function() {
return {
restrict: 'A',
replace: true,
scope: { item: '&' },
template: '<div id="item{{$index}}"></div>',
link: function($scope, element, attributes) {
element.append('<div>' + $scope.item.name + '</div>');
}
};
});
However, inside the linking function, $scope.item.name yields undefined. I'm wondering if there is any way I could access the repeated item inside my directive.
If not, what would be my alternatives? Move the ng-repeat inside the directive, maybe?
P.S. I know that you should (generally speaking) not do DOM manipulation this way, but since I might have ~2000 items that would result in 6000 bindings, and I'm afraid that would lead to severe performance issues.
You should pass item as attribute to directive created a sample directive
http://plnkr.co/edit/l5r6zIc7ncT1XldRuB98?p=preview
Related
What I'm trying to achieve is relatively simple, but I've been going round in circles with this for too long, and now it's time to seek help.
Basically, I have created a directive that is comprised of a text input and a link to clear it.
I pass in the id via an attribute which works in fine, but I cannot seem to work out how to pass the model in to clear it when the reset link is clicked.
Here is what I have so far:
In my view:
<text-input-with-reset input-id="the-relevant-id" input-model="the.relevant.model"/>
My directive:
app.directive('textInputWithReset', function() {
return {
restrict: 'AE',
replace: 'true',
template: '<div class="text-input-with-reset">' +
'<input ng-model="inputModel" id="input-id" type="text" class="form-control">' +
'<a href class="btn-reset"><span aria-hidden="true">×</span></a>' +
'</div>',
link: function(scope, elem, attrs) {
// set ID of input for clickable labels (works)
elem.find('input').attr('id', attrs.inputId);
// Reset model and clear text field (not working)
elem.find('a').bind('click', function() {
scope[attrs.inputModel] = '';
});
}
};
});
I'm obviously missing something fundamental - any help would be greatly appreciated.
You should call scope.$apply() after resetting inputModel in your function where you reset the value.
elem.find('a').bind('click', function() {
scope.inputModel = '';
scope.$apply();
});
Please, read about scope in AngularJS here.
$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.
I've also added declaring of your inputModel attribute in scope of your directive.
scope: {
inputModel: "="
}
See demo on plunker.
But if you can use ng-click in your template - use it, it's much better.
OK, I seem to have fixed it by making use of the directive scope and using ng-click in the template:
My view:
<text-input-with-reset input-id="the-relevant-id" input-model="the.relevant.model"/>
My directive:
app.directive('textInputWithReset', function() {
return {
restrict: 'AE',
replace: 'true',
scope: {
inputModel: '='
},
template: '<div class="text-input-with-reset">' +
'<input ng-model="inputModel" id="input-id" type="text" class="form-control">' +
'<a href ng-click="inputModel = \'\'" class="btn-reset"><span aria-hidden="true">×</span></a>' +
'</div>',
link: function(scope, elem, attrs) {
elem.find('input').attr('id', attrs.inputId);
};
});
It looks like you've already answered your question, but I'll leave my answer here for further explanations in case someone else lands on the same problem.
In its current state, there are two things wrong with your directive:
The click handler will trigger outside of Angular's digest cycle. Basically, even if you manage to clear the model's value, Angular won't know about it. You can wrap your logic in a scope.$apply() call to fix this, but it's not the correct solution in this case - keep reading.
Accessing the scope via scope[attrs.inputModel] would evaluate to something like scope['the.relevant.model']. Obviously, the name of your model is not literally the.relevant.model, as the dots typically imply nesting instead of being a literal part of the name. You need a different way of referencing the model.
You should use an isolate scope (see here and here) for a directive like this. Basically, you'd modify your directive to look like this:
app.directive('textInputWithReset', function() {
return {
restrict: 'AE',
replace: 'true',
template: [...],
// define an isolate scope for the directive, passing in these scope variables
scope: {
// scope.inputId = input-id attribute on directive
inputId: '=inputId',
// scope.inputModel = input-model attribute on directive
inputModel: '=inputModel'
},
link: function(scope, elem, attrs) {
// set ID of input for clickable labels (works)
elem.find('input').attr('id', scope.inputId);
// Reset model and clear text field (not working)
elem.find('a').bind('click', function() {
scope.inputModel = '';
});
}
};
});
Notice that when you define an isolate scope, the directive gets its own scope with the requested variables. This means that you can simply use scope.inputId and scope.inputModel within the directive, instead of trying to reference them in a roundabout way.
This is untested, but it should pretty much work (you'll need to use the scope.$apply() fix I mentioned before). You might want to test the inputId binding, as you might need to pass it a literal string now (e.g. put 'input-id' in the attribute to specify that it is a literal string, instead of input-id which would imply there is an input-id variable in the scope).
After you get your directive to work, let's try to make it work even more in "the Angular way." Now that you have an isolate scope in your directive, there is no need to implement custom logic in the link function. Whenever your link function has a .click() or a .attr(), there is probably a better way of writing it.
In this case, you can simplify your directive by using more built-in Angular logic instead of manually modifying the DOM in the link() function:
<div class="text-input-with-reset">
<input ng-model="inputModel" id="{{ inputId }}" type="text" class="form-control">
<span aria-hidden="true">×</span>
</div>
Now, all your link() function (or, better yet, your directive's controller) needs to do is define a reset() function on the scope. Everything else will automatically just work!
I'm looking to create a custom directive that will take a template as a property of a configuration object, and show that template a given number of times surrounded by a header and footer. What's the best approach to create such a directive?
The directive would receive the configuration object as a scope option:
var app = angular.module('app');
app.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
config: '=?'
}
...
}
}
This object (called config) is passed optionally to the directive using two way binding, as show in the code above. The configuration object can include a template and a number indicating the number of times the directive should show the template. Consider, for example, the following config object:
var config = {
times: 3,
template: '<div>my template</div>'
};
It would, when passed to the directive, cause the directive to show the template five times (using an ng-repeat.) The directive also shows a header and a footer above and below the template(s):
<div>the header</div>
<div>my template</div>
<div>my template</div>
<div>my template</div>
<div>the footer</div>
What's the best way to implement this directive? Note: When you reply, please provide a working example in a code playground such as Plunker, as I've run into problems with each possible implementation I've explored.
Update, the solutions I've explored include:
The use of the directive's link function to append the head, template with ng-repeat, and footer. This suffers from the problem of the template not being repeated, for some unknown reason, and the whole solutions seems like a hack.
The insertion of the template from the configuration object into middle of the template of the directive itself. This proves difficult because jqLite seems to have removed all notion of a CSS selector from its jQuery-based API, leading me to wonder if this solution is "the Angular way."
The use of the compile function to build out the template. This seems right to me, but I don't know if it will work.
You could indeed use ng-repeat but within your directive template rather than manually in the link (as that wouldn't be compiled, hence not repeated).
One question you didn't answer is, should this repeated template be compiled and linked by Angular, or is it going to be static HTML only?
.directive('myDirective', function () {
return {
restrict: 'E',
scope: {
config: '=?'
},
templateUrl: 'myTemplate',
link: function(scope) {
scope.array = new Array(config.times);
}
}
}
With myTemplate being:
<header>...</header>
<div ng-repeat="item in array" ng-bind-html="config.template"></div>
<footer>...</footer>
I'd think to use ng-transclude in this case, because the header & footer wrapper will be provided by the directive the inner content should change on basis of condition.
Markup
<my-directive>
<div ng-repeat="item in ['1','2','3']" ng-bind-html="config.template| trustedhtml"><div>
</my-directive>
Directive
var app = angular.module('app');
app.directive('myDirective', function($sce) {
return {
restrict: 'E',
transclude: true,
template: '<div>the header</div>'+
'<ng-transclude></ng-transclude>'+
'<div>the footer</div>',
scope: {
config: '=?'
}
.....
}
}
Filter
app.filter('trustedhtml', function($sce){
return function(val){
return $sce.trustedHtml(val);
}
})
I have a timeline.json like:
[{
"from":"twitter",
//...
},
{
"from": "facebook"
//...
}]
Based on from attribute I need "render" specific directives: post-twitter or post-facebook Inside a loop
How could I do that?
There are several ways. You can use ng-switch, ng-if, or a custom handler function in the link phase. You can find more info in the documentation.
Basically, switch between tags that invoke the directive based on a conditional statement, being it the 'from' value in your model. You can combine for example the ng-if directive with ng-include, to render a portion of your template based on this condition. Just make sure it won't degrade the performance.
You can create a directive which compiles wanted directive depending on the passed argument.
Something like:
.directive('renderOther', function($compile) {
return {
restrict: 'E',
scope: {
type: '='
},
link: functtion(scope, elem, attrs) {
var dir = $('<post-' + scope.type + '></post-'+scope.type+'>');
dir.appendTo(elem);
$compile(elem.contents())(scope);
}
}
});
Html:
<div ng-repeat="i in items">
<render-other type="i.from"></render-other>
</div>
(Its not working code - just an idea)
I have angular-ui/ui-select working fine as below:
ui-select(multiple="" name="resourceSelector" ng-model="appointmentTemplate.resources")
ui-select-match(placeholder="Select Resources")
span {{$item.name}}
ui-select-choices(repeat="resource in resources | filter: {name:$select.search}")
div {{resource.name}}
When appointmentTemplate.resources is populated like when the view loads, the resource shows as it should in the element.
I have tried to wrap it in a directive (my first). The directive won't show the supplied appointmentTemplate.resources. I can select new ones and save them fine, just not display the existing ones. I have confirmed the data is there using ng-inspector. Here is the directive controller:
angular.module('app').directive('resourceMultiSelector', function(){
return {
restrict: 'E',
scope: {
ngModel: '=',
placeholder: '#'
},
controller: function($scope, zResource, $sce){
zResource.query(function(resources){
$scope.resources = resources;
});
},
templateUrl: "/partials/common/resourceMultiSelector"
};
});
And here is the directive template (in Jade):
ui-select(multiple="" ng-model="$parent.ngModel")
ui-select-match(placeholder="{{placeholder}}")
span {{$item.name}}
ui-select-choices(repeat="resource in resources | filter: {name:$select.search}")
div {{resource.name}}
I use the directive like this:
resource-multi-selector(ng-model="appointmentTemplate.resources" placeholder="Select resources" )
What am I missing here?
Duh. So the objects in the list need to be from the list of choices, not just identical, but the same actual object. Obvious in retrospect I guess :/
I have directive this directive:
myApp.directive('myDirective',['$http', function($http) {
return {
restrict: 'AEC',
replace: true,
scope: { attr1: '=' , attr2: '=' },
link: function(scope, element, attrs) {
...
}
}]);
If I put directive inner ng-repeat it works, so I have acces to value of attributes (eg. scope.attr1)
<div ng-repeat="item in items"
<my-directive attr1="item.value1" attr2="item.value2"></my-directive>
</div>
but if I put directive outside ng-repeat, so I have only my-directive:
{{mymodel.value1}} {{mymodel.value2}} //{{}} print correct value
<my-directive attr1="mymodel.value1" attr2="mymodel.value2"></my-directive> //this fail
I can't access to attributes, so If I access eg. scope.attr1 I'm getting undefined value.
the "item" object is only defined in the div with the ngRepeat so when you are trying to access specific items from the list "items" outside of the div with ngRepeat you have to use items[index].value1 syntax. Try:
<my-directive attr1="items[index].value1" attr2="items[index].value2"></my-directive>
If the values are simple types, you should use '#' instead of the two-way model binding that '=' implies.
Also how are you reading your values. Do you read them through scope.attr1 or attrs['attr1'] - since the attr collection only holds the value in the attributes, whereas the scope actually lnks to the objects
There should be nothing wrong with your code. Maybe you could spot what you're doing differently:
Working Example Here