Setting HTML as attributes with directive/$compile
-
21-12-2019 - |
Domanda
the controller of my module has a property as a string in which I assemble HTML.
Within a directive I try to assign the HTML-string to an attribute of tooltip, that is "tooltip-html-unsafe".
I am able to assign the whole element to this tooltip-attribute. How can I acess the property of the parent scope?
Please see my plunkr for the code given: http://plnkr.co/edit/rTq8zrKdc3qABrc9Tde6?p=catalogue
Soluzione
Two things:
- You need to update the value of $scope.contentHTML (just setting the var value isn't updating the $scope value). If you want to just read that value from your directive, you can access it in your linking function with
scope.contentHTML
. If you want to be able to set the parent scope's contentHTML property from your directive, you can use the scope property in your directive and set the value to "=". Then you can access it from
scope
in your linking function. For example:app.directive("tooltipView", function($compile) { return { restrict: "AE", scope: { tooltipView: "=" }, link: function(scope, element, attrs) { console.log(scope.tooltipView); } }; });
If you plan to use the "="
sign value for scope in your directive (Number 2 above), you also need to tell your directive which scope value to map to in your HTML. So:
<p tooltip-view="contentHTML">Hello {{name}}!</p>
would map scope.tooltipView in your linking function to $scope.contentHTML in your controller.
See the plunkr based off yours: http://plnkr.co/edit/HskBFNRW8mC8QmVWr3hP
Altri suggerimenti
To access parent scope from current one you can do:
scope.$parent.someValue