Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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] http://errors.angularjs.org/1.2.0rc1/$rootScope/inprog?p0=%24apply

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

like image 882
Steve Avatar asked Sep 27 '13 07:09

Steve


1 Answers

Escape the isolated scope with "dotted model" reference:

<html ng-app>
  <head>
    <script src="http://code.angularjs.org/1.1.5/angular.min.js"></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>

    <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>
    </script>

  </head>
  <body>

    <div ng-controller="Ctrl">

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

    </div>

  </body>
</html>
function Ctrl($scope) {
  $scope.tpl = {};
  $scope.tpl.contentUrl = '/partials/testScriptForm.html';
}
like image 177
Stewie Avatar answered Oct 08 '22 21:10

Stewie