If you are looking to create a catch-all feature where attributes prefixed with, for example, my
, are evaluated and then set to their respective non-prefixed attribute values, you will need to:
- Create a custom directive.
- Retrieve all attributes on the element (accessible via $attrs).
- Evaluate the attribute value.
- Set the actual attribute on the element.
I won't go into detail on creating the directive itself, but you can learn more about it here.
Within the link
function of your directive, one of the arguments passed in will be $attrs. $attrs
contains both the normalized (camel-cased) and non-normalized attribute names, along with their respective evaluated values (if using expressions), as well as some helper methods.
You can iterate over the keys of $attrs (or $attrs.$attr), filter out any unwanted keys like ng-model or ng-selected, evaluate the value, and set the corresponding non-prefixed attribute.
Object.keys($attrs).filter(function(key){
// Filter out unwanted keys like ngModel, ngSelect, etc.
return /^my/.test(key);
}).forEach(function(key){
// $attrs.$attr contains the non-normalized versions of the attributes
// This example assumes you'll prefix with `my`
// Remove 'my-' to get the attribute name to set
var attrName = $attrs.$attr[key].replace("my-","");
// Use $parse() if you want to use a scope property name
// For example, my-attribute="somePropertyName"
$attrs.$set(attrName,$parse($attrs[key])($scope));
// Just use $attrs[key] if using an expression
// For example, my-attribute="{{somePropertyName}}"
$attrs.$set(attrName,$attrs[key]);
});
angular.module("test",[])
.controller("ctrl",function($scope){
$scope.someprop = "Some Value";
})
.directive("caAttr",function($parse){
return {
restrict : 'A',
link : function($scope, $element, $attrs) {
console.log($attrs);
Object.keys($attrs).filter(function(key){
return /^my/.test(key);
}).forEach(function(key){
var attrName = $attrs.$attr[key].replace("my-","");
$attrs.$set(attrName,$parse($attrs[key])($scope));
});
angular.element("#log").text( angular.element("#container").html() );
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="ctrl">
<div id="container">
<div ng-model="mymodel" ng-selected="{{nothing}}" my-stack="someprop" ca-attr></div>
</div>
<div id="log"></div>
</div>