Steve Steve - 1 month ago 4x
AngularJS Question

AngularJS ngInclude dynamically changing its location

I have a few partial templates where the location is changed based on user actions via ng-click:

<div ng-include="contentUrl"></div>

<button ng-click="contentUrl = '../partials/testScriptForm.html'">Add Test Script</button>

This works great unless I the button above is inside of the partial itself, so if testScriptForm.html has a button:

<button ng-click="contentUrl = '../partials/testScriptCase.html'">Add Test Case</button>

Then nothing happens.

This seems due to ng-include getting a new (inherited but not shared?) scope.

What I can't figure is how to get the included template (partial) to change its own location.

I did try a function to change the $scope.$parent.contentUrl, it does seem to change but not "propagate" the changes.

In coffeescript:

$scope.changeParentLocation = (location) ->
$scope.$parent.contentUrl = location

Also tried to $scope.$apply() and $scope.$parent.$apply() in there and get the error:

Error: [$rootScope:inprog]$rootScope/inprog?p0=%24apply

Maybe I'm just mis-using includes...


Escape the isolated scope with "dotted model" reference:

<html ng-app>
    <script src=""></script>
    <script src="script.js"></script>

    <script type="text/ng-template" charset="utf-8" id="/partials/testScriptForm.html">
      <h1>This is testScriptForm.html</h1>
      <button ng-click="tpl.contentUrl = '/partials/testScriptCase.html'">Change to Test Case</button>

    <script type="text/ng-template" charset="utf-8" id="/partials/testScriptCase.html">
      <h1>This is testScriptCase.html</h1>
      <button ng-click="tpl.contentUrl = '/partials/testScriptForm.html'">Change to Test Form</button>


    <div ng-controller="Ctrl">

        <div ng-include="tpl.contentUrl"></div>


function Ctrl($scope) {
  $scope.tpl = {};
  $scope.tpl.contentUrl = '/partials/testScriptForm.html';