I want to make a custom directive that makes decisions based on the model that is being passed. I followed an example that looks a lot like what I want to do, here .
In the end, I pass a JSON address to the directive using this code snippet:
<div><b>Address</b>
<address-source address="company.address"/>
</div>
This is the directive:
AppDirectives.directive('addressSource', function ($compile) {
var template = '<span> {{address.id}} </span>';
var getTemplate = function(scope) {
console.log("address id: " + scope.address.id);
return template;
};
var linker = function(scope, element, attrs) {
element.html(getTemplate(scope)).show();
$compile(element.contents())(scope);
};
return {
restrict: "E",
replace: true,
link: linker,
scope: {
address: '='
}
};
});
The address is in scope, and the {{ address.id }}
is resolved. However, when I want to do calculations with it, like logging it to the console, an error shows up that scope.address is undefined. What am I doing wrong? I see no differences with the working example.
when I want to do calculations with it, like logging it to the console
Where are you doing those calculations? If it is not in the linker
function then you won't have access to the address as it lives in the isolated scope you requested when you wrote:
scope: {
address: '='
}
Remove .show() From this.
element.html(getTemplate(scope)).show();
Like:
element.html(getTemplate(scope));
SEE DEMO
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.