Izaskun Peña Izaskun Peña - 6 months ago 51
AngularJS Question

Insert AngularJS directives (ng-click) in plain html

I want to insert specific AngularJS code within a plane HTML, and to compile it looks like this:

<a ng-click="viewUserstory(567456436)>


To do this, I have done the following:
In my service:

function parseScrumEvents(scrumMessageJSON) {

var messageText = "<p><strong> #" + scrumMessageJSON.num + " </strong>" +
"<a ng-click='viewUserstory("+scrumMessageJSON.userstory.id+")'>scrumMessageJSON.subject</a> </p>";

return messageText;

};


In my controller:

$scope.viewUserstory = function (userstoryid){
console.log(userstoryid);
};

$scope.getScrumMessage = function ($index) {
var scrumMessageString = $scope.listaMensajes[$index].text;
var scrumMessageMiddle = JSON.parse(scrumMessageString);
var messageText = ScrumParseService.parseScrumEvents(scrumMessageMiddle);

return messageText;

};


In my HTML:

<span bind-html-compile="getScrumMessage($index)"></span>


In my directive:

angular.module('myAppAngularMinApp')
.directive('bindHtmlCompile', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(function () {
return scope.$eval(attrs.bindHtmlCompile);
}, function (value) {
// In case value is a TrustedValueHolderType, sometimes it
// needs to be explicitly called into a string in order to
// get the HTML string.
element.html(value && value.toString());
// If scope is provided use it, otherwise use parent scope
var compileScope = scope;
if (attrs.bindHtmlScope) {
compileScope = scope.$eval(attrs.bindHtmlScope);
}
$compile(element.contents())(compileScope);
});
}
};
}]);


But, my browser console returns me error:

Error: [$parse:syntax] Syntax Error: Token 'b73ecf1f7b15315359e96' is unexpected, expecting [)] at column 18 of the expression [viewUserstory(574b73ecf1f7b15315359e96)] starting at [b73ecf1f7b15315359e96)].


I have no idea how to program it to work.
If you know other ways to do it, also would be helpful.
Any ideas?
Thank you very much for your help :D

Answer

You need to use quotes (simples or doubles) and surround your dynamic value.

Your service should lool like this:

function parseScrumEvents(scrumMessageJSON) {

  var messageText = "<p><strong> #" + scrumMessageJSON.num + " </strong>" +
        "<a ng-click='viewUserstory(" + '"'+scrumMessageJSON.userstory.id+'"'+")'>scrumMessageJSON.subject</a> </p>";

  return messageText;
};

It could happen because angular thinks that your dyinamic value passed in your function in the ng-clik binding is a identifier ( name of a variable in your scope).

I guess you're trying to pass a value to your function, based on that, you need to use quotes.

Comments