I'm trying to create a simple application using AngularJS and TimelineJS3 but I'm having a problem with it.
I have a state (timeline) which contains a partial view (timeline.html
) associated with a controller. This state contains a promise to fetch data from the server, which is going to be stored in the $scope
variable inside the controller. The problem is that I need to access this variable inside a <script>
tag in the partial view file.
Here's the code:
app.js
app.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider){
.state('timeline', {
url: '/timelines/:id',
views: {
'partial-timeline': {
templateUrl: 'partial/timeline.html',
controller: 'TimelineController'
}
},
resolve: {
getOneTimeline: ['$stateParams','timelineServ', function($stateParams, timelineServ) {
return timelineServ.getTimelineById($stateParams.id);
}]
}
});
}]);
app.controller('TimelineController', ['$scope', 'timelineServ',
function($scope, timelineServ) {
$scope.timelineData = timelineServ.indivTimeline;
}]);
timeline.html
{{timelineData}}
<div id="timeline-embed" style="width: 100%; height: 600px"></div>
<script type="text/javascript">
window.timeline = new TL.Timeline('timeline-embed', {{timelineData}});
</script>
From the {{timelineData}}
expression outside I can see that the variable has the correct data however, as I said, I'm not able to use it inside the <script>
tags.
What is the best approach to solve this problem? I'm quite new to AngularJS.
Thank you in advance. Best Regards!
I managed to make it work :)
On app.js, the code related to the definition of the state timeline remained the same. Additionally, I created a new directive:
app.directive('runTimelineScript', function() {
return {
restrict: 'E',
link: function (scope, element, attr) {
window.timeline = new TL.Timeline('timeline-embed', timelineData);
}
};
});
And modified the controller to look like this:
app.controller('TimelineController',
['$scope', 'timelineServ', function($scope, timelineServ) {
window.timelineData = timelineServ.indivTimeline;
}]);
Then, in the html file for the partial view (timeline.html), I just inserted the new directive:
<div id="timeline-embed" style="width: 100%; height: 600px"></div>
<run-timeline-script></run-timeline-script>