Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

this has been bugging me for days and i can't figure this out. i have a website that adds articles at certain points so i figured i shouldn't need to change the routing every time i add a page. so i added this to my project:

 $routeProvider.when ('/pages/:page', { templateUrl: 'page.html', controller: 'pageCtrl' });

then i use this for the pageCtrl:

 app.controller('pageCtrl', function ($scope, $http, $q, $routeParams, $sce, $location) {
  $http.get("partials/" + $routeParams.page + ".html")
  .then(function(ret) {
    $scope.content = $sce.trustAsHtml(ret.data);
  }, function(err) {
    $location.path("/404")
  });
 });

then in the webpage i put a

 <div ng-view ng-bind-html="content">{{content}}</div> 

and all works well except when i put angular code in there. it seems that it will only parse regular html code but not the ng-stuff. i think i should put a $compile in there somewhere. but i tried all combinations i could think of but none work.

things i tried:

 $scope.content = $compile($sce.trustAsHtml(ret.data))($scope);

 var e=angular.element($sce.trustAsHtml(ret.data));
 c=$compile(e);
 $scope.content = c;
 c($scope);

and several others that didnt do anything at all..

what's the right way to add content in a view and have angular directive work properly?

share|improve this question
    
Why can't you just add to your view: <div ng-include="page"></div> and set $scope.page = $routeParams.page; – New Dev Dec 3 '14 at 2:20
    
i think ng-include only works at page-load. if you load the page in a route afterwards it will re-enter the controller until it runs into an error: Error: error:infdig Infinite $digest Loop – user3432565 Dec 3 '14 at 16:22

1 Answer 1

up vote 0 down vote accepted

This should work well with ng-include within your page.html template:

page.html:

<h1>Page {{name}}</h1>
<div ng-include="contentUrl"></div>

Then your pageCtrl can set these to:

app.controller("pageCtrl", function($scope, $routeParams){
  $scope.name = $routeParams.page;
  $scope.contentUrl = $routeParams.page + ".html";
})

Here's a working plunker

share|improve this answer
    
actually that works like a charm. i think i tried that but got the infinite loop error. probably made a typo somewhere. copy/paste did the trick! thanks :) – user3432565 Dec 3 '14 at 22:51
1  
quick addition. because this method doesn't detect whether the page actually exists, i added this to the controller to redirect it to my custom 404 page: ` $scope.$on('$includeContentError', function(event) { $location.path("/404"); console.log("Error"); });` – user3432565 Dec 3 '14 at 23:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.