angularJS how to change attrs in directive's link - javascript

I set a progress in my app
I want to controll The progress in angular's directive
but how can I change data-value and data-total in directive's link func?
app.html
<div class="ui indicating small progress" data-value="39" data-total="50" plan-progress>
<div class="bar">
<div class="progress"></div>
</div>
</div>
In this html, I want change data-value and data-total
I try this:
app.js
todoApp.directive('planProgress', function() {
return {
link: function(scope, elem, attrs) {
attrs.value = 10
attrs.total = 20
elem.progress();
}
};
});
But it doesn't work
so I want to know how to change it in my directive?

Use attrs.$set() in your link function and recompile the element. Also, don't forget to inject the $compile service to your directive.
In your html you've added the directive as an attribute but didn't mention it in the restrict value in your directive definition. You need to mention it in directive definition.
See the code bellow:
todoApp.directive('planProgress', function($compile) {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
attrs.$set('value', 10);
attrs.$set('total', 20);
$compile(elem)(scope);
}
};
});

Simply use :
attrs["data-value"] = 10;
attrs["data-total"] = 20;
You don't want to use attrs.data-total = 20 because the - will force a subtraction.
It's always legal in javascript to use x[keyName] instead of x.keyName, and you must use this second notation when keyName is a strange key such as **$^ùjsls* or data-value. A more useful case is when the key is a variable.
On last thing : as you do, you will always rewrite the coder's inputs. It may have sense, but it's not very elegant.

Related

angular directive: switch between two templates dynamically

I am trying to create a directive named availableTo that can switch between two different templates depending on some message. For example, if the field is an input with the ng-model directive, I would first need to change it to read-only using the <span> tag. So far, my code can switch the view to read-only, but I cannot seem to switch it back to input:
var directive = {
restrict: 'A',
require: '?ngModel',
link: linkerFn,
replace: true
};
function linkerFn(scope, element, attrs, ngModelCtrl) {
var clonedElement = angular.copy(element);
var preOuterHTML = clonedElement[0].outerHTML; //this can save the <input> field html code
scope.$on('mode_changed', function() {
var curUserRole = userservices.getUserRole();
if (attrs.availableTo == curUserRole) {
var e = $compile(preOuterHTML)(scope);
element.replaceWith(e);
} else {
var template = '<span>' + ngModelCtrl.$viewValue + '</span>';
var e = $compile(template)(scope);
element.replaceWith(e);
}
}); //scope.$on
} //linkerFn
For an input field:
<input name="test1" class="form-control" ng-model="name" placeholder="Name 1" available-to="ADMIN"/>
I also noticed that once I change the template in the else block above, the element re-renders, and the preOuterHTML does not contain the original element html any more. This seems to be mission impossible to me, but I would like to hear some expert opinions. Thanks
element.replaceWith(e); Don't do that. In Angular, if you find yourself attempting to modify the DOM directly, you are by definition doing it wrong. You gotta sit back and let Angular do the work.
If you need to replace a directive's entire template, a fairly straightforward approach is to use ng-include with a scope variable containing the desired conditional templateUrl, e.g.
var directive = {
// ...
template: '<div ng-include="myTemplateUrl"></div>',
link: function(scope, el) {
if (/* whatever */) {
scope.myTemplateUrl="templates/foo.html";
} else {
//...etc
}
},
};
(This does add an extra DOM node to the tree, but that's generally harmless.)
It sounds like in your case you may not need to go that far, though; a simple ng-if inside your template is probably enough to swap between your read-only <span> and <input>.

AngularJS - inject string from model to HTML's tag name

is it possible to inject string into html's tag name with angular?
Something like this:
<div ng-repeat="type in types">
<bettype-{{type.id}}></bettype-{{type.id}}>
</div>
The output I need is:
<bettype-1></bettype-1>
<bettype-2></bettype-2>
I am also using polymer (this way I am creating the custom html tags).
I think the best solution would be to create a directive which creates custom elements, something like:
.directive('bettype', function($compile) {
return {
restrict: 'E',
compile: function($element, $attr) {
return function($scope, $element, $attr) {
// Create new element here with $attr.number
var number = $attr.number,
element = angular.element('<bettype-'+number+'></bettype-'+number+'>');
// Replace newly created element
$element.replaceWith(element);
$compile($element)($scope);
}
}
}
});
Not sure if that will work, but probably that's the way to go...
Note: I don't think it\s a good idea to have dashed separated elements like bettype-1..

AngularJS ng-switch without extra DOM

I have a custom directive and an object myObj on the current $scope (inside an ng-repeat).
If the object has a type of html, I want to use one template:
<span ng-bind-html="myObj.html"></span>`
Otherwise I want to use a different template:
<span>{{myObj.value}}</span>`
My problem
This is invalid because a custom directive template must contain exactly one root node:
<span ng-if="myObj.type==='html'" ng-bind-html="myObj.html"></span>
<span ng-if="myObj.type!=='html'">{{myObj.value}}</span>
This is invalid because it destroys my page with extra DOM: (wrapping all my spans (there could be thousands) in unnecessary ng-switch nodes...)
<ng-switch on="myObj.type">
<span ng-switch-when="html" ng-bind-html="myObj.html"></span>
<span ng-switch-default>{{myObj.value}}</span>
</ng-switch>
My Question
Is it possible to have a directive pick it's template based on the result of a switch, without creating extra unnecessary DOM? For example, you can specify replace: true when creating a directive - is it possible to similarly have an ng-switch where the result replaces the switch tag itself?
Edit
My Directive:
return {
replace: true,
controller: 'ChunkController',
scope: {
chunk: '=deChunk'
},
templateUrl: de.partial.chunk,
link: function (scope, el, attr, ctrl) {
el.on('keydown', handleKeypress.bind(ctrl));
el.on('click', ctrl.showValue);
}
};
And its usage:
<div class="content" contenteditable="{{node.type!=='static'}}">
<div data-ng-repeat="chunk in node.chunks" data-de-chunk="chunk"></div>
</div>
With the intent that the child <div> will be replaced with the sequence of <span>s from above.
I wouldn't even bother if you are storing the html in a service just check to see if a value for myObj.html exists in the object and if it does compile and bind the html in the linker function instead of using ng-bind-html
something like this maybe:
myapp.directive('something',function($compile){
return {
link: function(scope,elem,attrs) {
var obj = scope.$eval(attrs.something);
if(obj.html) {
var html = angular.element($compile(obj.html)(scope));
elem.append(html);
} else {
//go get the data and set obj.html
}
}
}
});

AngularJS: Truncate multi-line HTML bound in ng-repeat/ng-bind-html

I have following ng-repeat
<div class="item-post" ng-repeat="item in items">
<div class="item-content" ng-bind-html="item.text"></div>
</div>
where item.text is multi-line HTML text and it displays correctly, but I need to truncate it to max-height of item-post div (250px). And then append three dots signalizing that text is longer.
I wanted to use jquery.autoellipsis which is working for example on div with static content.
For AngularJS I have found angular-ellipsis, but is doesn't work with HTML, only plain text. I need to achieve it on HTML content.
Thanks in advance for help!
EDIT/SOLUTION:
Finally I have been able to use jquery.autoellipsis plugin using custom directive (based on asgoth's answer):
myDirectives.directive('htmlEllipsis', ['$timeout', function($timeout) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$timeout(function() {
angular.element(element).ellipsis();
}, 0);
}
};
}]);
And in partial view:
<div class="item-post" ng-repeat="item in items">
<div class="item-content" ng-bind-html="item.text" html-ellipsis></div>
</div>
EDIT2:
Directive from asgoth's answer after his edit works well, using another approach than above-mentioned directive.
If I were you I would make a directive to use the jquery plugin (jquery.autoellipsis):
angular.module('myModule').directive('ellipsis', [function () {
return {
required: 'ngBindHtml',
restrict: 'A',
priority: 100,
link: function ($scope, element, attrs, ctrl) {
$scope.hasEllipsis = false;
$scope.$watch(element.html(), function(value) {
if (!$scope.hasEllipsis) {
// apply ellipsis only one
$scope.hasEllipsis = true;
element.ellipsis();
}
});
}
};
}]);
Your html is then:
<div class="item-content" ng-bind-html="item.text" ellipsis></div>
Of course, you need to include the jquery plugin in a script tag.
EDIT: I've edited the answer, so the directive will watch for the html to change (done by ngBindHtml).
Similar to the accepted answer, this alternative allows improved customization: https://github.com/dibari/angular-ellipsis

Access template child elements in angular directive

I'm trying make a directive out of a great jquery zooming/panning library. How can I access the elements in my template to initialize the plugin?
The directive looks like this as of now:
directive('zui', [function () {
return {
restrict: 'E',
scope: { URL: "#"},
template: '<div id="zui" ><div id="viewport" ><img ng-src="{{imageURL}}"></div></div>',
link: function (scope, element, attrs) {
scope.imageURL = URL;
var zui = new ZUI53.Viewport( document.getElementById('zui') );
zui.addSurface( new ZUI53.Surfaces.CSS( document.getElementById('viewport') ) );
var pan_tool = new ZUI53.Tools.Pan(zui);
zui.toolset.add( pan_tool );
pan_tool.attach()
}
};
}]);
Clearly document.getByID() is not the best way to accomplish this. What is a better solution? Thanks a lot.
Getting to the element using document.getElementById('zui') is indeed not nice. If you ever had to have two instances of the zui directive, it would break.
Don't use id on the root element. Use a marker class
such as class="zui" or a data attribute such as data-zui.
Using jquery, you can get to your element using find like
this: element.find('.zui')[0];.

Categories