Jokingpsh Jokingpsh - 6 months ago 67
Javascript Question

Access Angular variable within script tag

I am making a web app:front-end in Angular and backend in Rails.
I am using LinkedIn's member profile plugin which shows person's profile based on URL being passed. Here is the code for this plugin.

<script src="//platform.linkedin.com/in.js" type="text/javascript"></script>
<script type="IN/MemberProfile" data-id="(Your LinkedIn URL)" data-format="inline" data-related="false"></script>


I want to make data-id part dynamic. Basically, I will let my users to write their linkedin address in text box and save it to Angular's variable. When the value changes, I want that value gets assigned to
data-id
. But I'm not sure whether
data-id
can access a variable in Angular.

Answer

Quite simple. Create your app along with a global controller that will be initialised on your html tag like so:

<html ng-app="app" ng-controller="myctrl">
  <head>
     <script type="IN/MemberProfile" data-id="{{myId}}" data-format="inline" data-related="false"></script>
  </head>
</html>

And have this as your controller and app initialisation, or something similar:

var app = angular.module('app', []);
app.controller('myctrl', ['$scope', function($scope){
  $scope.myId = 123;
}]);

To break it down, $scope.myId will be assigned the LinkedIn ID, and it is output on the page inside the head tag (I'm guessing that's where you want it) within the data-id attribute on the script tag.

WORKING EXAMPLE