Is there any way to achieve what I'm trying to do in this fiddle?
I want to add a directive to an element using an Angular expression.
Example:
<div {{hello}}></div>
Is there any way to achieve what I'm trying to do in this fiddle?
I want to add a directive to an element using an Angular expression.
Example:
<div {{hello}}></div>
You need to insert the div inside the controller and not in the html markup in order to create directive dynamically. Over here I have used the $compile service inorder to dynamically generate the directive according the scope variable hello.
Controller Code:
function MainCtrl($scope, $compile) {
$scope.flag = "disabled";
$scope.hello = "hello";
var el = $compile("<div " + $scope.hello + "></div>")($scope);
var element = angular.element(document.querySelector('#mainID'));
element.append(el);
}
I can see the idea but I'm not sure that's the appropriate place to declare your element. I would stick to attributes separate by type, or like @V31 where you create elements based on directives although his example seems to just create an element after the directive has compiled, I think you would need to recompile your directive again after that. Moreover I think the real power of your directive comes with it's ability to handle these events and maintain scope etc.
I would stick to attributes to declare your different element types, something like this -
restrict: "EA",
scope: {
ngModel: "=",
type: "@"
},
link: function (scope, el, attrs) { ...
Also ng-disabled already has an attribute for this.
ng-disabled="{{flag}}"