问题
I'm having an issue (just learning Angular) with a string having any /
removed and replaced with =""
.
I have a directive that takes it's element and then wraps it with a div
and provides some styling to the div
- namely a background-url
- it is the URL that is being replaced with something else.
It may be a little odd - what I am actually trying to do here - and that's ok; i'm just trying to learn a little more about Angular and simple manipulation of elements seems a good place to tinker..
Here is what I have:
HTML - notice the set-background
attribute on the image.
<div id="home">
<img src="~/Content/Images/Site/home-background.jpg" set-background />
</div>
Angular directive
dwApp.directive('setBackground', function () {
return {
restrict: 'A',
scope: {},
link: function (scope, element, attrs) {
element.addClass('backgroundCover');
var bgImg = 'style="background-image:url("' + attrs.src + '");'
element.wrap('<div class="backgroundCoverContainer" ' + bgImg + '></div>');
element.remove();
}
}
});
Resulting HTML - notice the background-url
<div id="home">
<div class="backgroundCoverContainer" style="background-image:url(" content="" images="" site="" home-background.jpg");=""></div>
</div>
If I console.log(bgImg)
I get:
style="background-image:url("/Content/Images/Site/home-background.jpg");
Clearly, the background-image
isn't actually being rendered like that though...
any ideas?
回答1:
Ok, so i'm an ass....
Charlietfl's comment put me in the right direction - thanks.
I was simply missing the closing "
to the style..
My JS WAS
var bgImg = 'style="background-image:url("' + attrs.src + '");'
When it should have been - notice the last "
var bgImg = 'style="background-image:url(' + attrs.src + ');"'
OR
var bgImg = 'style="background-image:url(\'' + attrs.src + '\');"'
Giving me the directive more like this - also removed the element.addClass - seeing as I was removing it anyway.... :D
dwApp.directive('setBackground', function () {
return {
restrict: 'A',
scope: {},
link: function (scope, element, attrs) {
var bgImg = 'style="background-image:url(\'' + attrs.src + '\');"'
element.wrap('<div class="backgroundCover" ' + bgImg + '></div>');
element.remove();
}
}
});
来源:https://stackoverflow.com/questions/20584471/angular-removing-from-strings-within-directive-seems-to-butcher-html