Search code examples
javascriptangularjsreturnreturn-value

ng-bind-html returning separate elements


How can I return these vars from my controller to use in my view as separate elements?

My controller.

.controller('AccountCtrl', function($scope, $sce) {
  $scope.sharelinks =function () {


    var myVar = x; //EDIT**

    var emailLink = '<a>Some info here (i use x)</a>'; //EDIT**

    var twitterLink = '<a>Some info here(i also use x)</a>'; //EDIT**

    var newMarkup = [emailLink,twitterLink];

    return $sce.trustAsHtml(newMarkup);
  };
})

View.

<div ng-bind-html="sharelinks[0]"></div>    
<div ng-bind-html="sharelinks[1]"></div>

Solution

  • Your sharelinks is a function, but used as an array. Try doing this:

    <div ng-bind-html="sharelinks()[0]"></div>    
    <div ng-bind-html="sharelinks()[1]"></div>
    

    Although I would just change it to something like:

    var emailLink = $sce.trustAsHtml('<a>Some info here</a>');
    var twitterLink = $sce.trustAsHtml('<a>Some info here</a>');
    
    $scope.sharelinks = [emailLink,twitterLink];
    

    And leave the view as it is.

    UPDATE: I've read your question once again. If you want to not use any arrays but just links straight, just put them on scope, like this:

    $scope.emailLink = $sce.trustAsHtml('<a>Some info here</a>');
    $scope.twitterLink = $sce.trustAsHtml('<a>Some info here</a>');
    

    And on the view:

    <div ng-bind-html="emailLink"></div>    
    <div ng-bind-html="twitterLink"></div>