I created ngMap,
and this directive does not watch any attribute values because attribute names are dynamic(too many cases).
However, I wanted to apply $observe to attribute only if directive users has given the attribute values to be dynamic using double curly brackets
I have tried here to detect if user uses double curly bracket using compile
function and link
function, but no luck yet.
To explain, from the following code
<body ng-app="myApp" ng-controller="MyCtrl">
<div my-dir foo="{{foo}}" bar="bar"></div>
</body>
I want to detect attribute foo
value is dynamic, but attribute bar
value is not.
I tried this code to check it, but not succeeded.
var app = angular.module("myApp", []);
app.controller('MyCtrl', function($scope) {
$scope.foo = "FOO";
});
app.directive('myDir', function() {
return {
compile : function(tele, tattr) {
return {
pre : function(scope, iele, iattrs) {
console.log('pre', iattrs); // this is the same as the below
},
post : function(scope, iele, iattrs) {
console.log('post', iattrs);
}
};
}
}
});
My question is how do I detect if an attribute value is dynamic by AngularJS or not?
You can check the non-interpolated value by getting the attribute value of the element itself, via elem.attr()
.
app.directive('myDir', function() {
return function(scope, elem, attr) {
var regex = /{{.*}}/;
if(regex.test(elem.attr('foo'))) {
attr.$observe('foo', function(value) {
// observe
console.log('observing foo');
});
}
if(regex.test(elem.attr('bar'))) {
attr.$observe('bar', function(value) {
// observe
console.log('observing bar');
});
}
}
});