Skip to content

Instantly share code, notes, and snippets.

@srfrnk
Last active August 29, 2015 14:05
Show Gist options
  • Save srfrnk/b3fb0c1fa8b48dab2bdf to your computer and use it in GitHub Desktop.
Save srfrnk/b3fb0c1fa8b48dab2bdf to your computer and use it in GitHub Desktop.
AngularJS directive that enables creating 'nugets' - html sections that may be embedded in several places within your template.
define("directives/nuget", ["app"], function (app) {
var nugets = [];
return app.directive('nuget', [function () {
return {
restrict: "E",
transclude: true,
link: function (scope, elm, attrs, ctrl, transclude) {
nugets.push({
name: attrs.name,
data: (attrs.data||"").split(','),
transclude: transclude
});
}
};
}]).directive('nuget', [function () {
return {
restrict: "A",
link: function (scope, elm, attrs) {
var nuget = nugets.filter(function (nugetI) {
return nugetI.name == attrs.nuget;
})[0];
var newScope = scope.$new();
newScope.nugetData = nuget.data.reduce(function (map, attr) {
var value;
if (attr[0] == '*') {
attr = attr.slice(1);
value = scope.$eval(attrs[attr]);
}
else {
value = attrs[attr];
}
map[attr] = value;
return map;
}, {});
elm.replaceWith(nuget.transclude(newScope, function () {}));
}
};
}]);
});
@srfrnk
Copy link
Author

srfrnk commented Aug 19, 2014

data attr sets comma seperated list of attributes that nuget can use. "*" before name means that the attribute value should be evaluated at scope level, other it is taken as a literal.

Usage: see very simple example at http://jsfiddle.net/srfrnk/f88mocLz/

@srfrnk
Copy link
Author

srfrnk commented Aug 19, 2014

<div ng-app="app" ng-init="ii=[1,2,3,4]">
    <nuget name="mynuget" data="name,*name1">
        <div>my nuget {{nugetData.name}} {{nugetData.name1+1}} {{i}}</div>
    </nuget>
    <div ng-repeat="i in ii">
        <div nuget="mynuget" name="my name" name1="i"></div>
        <div nuget="mynuget" name="my other name" name1="i"></div>
    </div>
</div>

@eranshapira
Copy link

nice, i liked the concept, hopefully will use it soon.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment