3

I'd like to understand how to load a view from a controller ?

Example, hypothetical:

myFile.html
<p>{{foo}}</p>

.controller("myCtrl", function(){
    $scope.html = loadFileHere("My foo", "myFile.html");
    console.log($scope.html);
});

I'd expect the output:
<p>My foo</p>

Is this possible to do ?

Thanks!

punkbit
  • 7,347
  • 10
  • 55
  • 89

1 Answers1

2

I am guessing you are talking about loading partials? You wouldn't really load a view with a controller, although MAYBE you could...I would use your routes to load a view. Your controller would return your scoped data to your partial view and then you would load it into an ng-view div or whatever. So for example...

in your app.js (or whatever you call it) assuming your myFile.html is in the same directory:

angular.
    module('app', []).
    config(['$routeProvider', function($routeProvider) {
        $routeProvider.
        when('/myFile', { templateUrl: 'myFile.html', controller: MyCtrl }).
        otherwise({ redirectTo: '/' });
}]);

Then maybe in a controllers.js file:

function MyCtrl($scope) {
    $scope.foo = "My foo";
}

And then in your myFile.html partial :

<p>{{foo}}</p>

And then your index.html file may look something like:

<!doctype html>
<html ng-app="app">
<head>
    <script src="js/angular.min.js"></script>
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
</head>
<body>
<div ng-controller="MyCtrl">
    <div class="container">

        <div ng-view></div>

    </div> <!-- /container -->
</div>
</body>
</html>
kevindeleon
  • 1,914
  • 3
  • 18
  • 30
  • Thanks for looking! I guess this is a bad practice, but I'm trying to avoid having to write some html in my controller. – punkbit Sep 26 '13 at 09:43
  • @heldrida I guess I just don't understand. There is no HTML in the controller I wrote above. The only html is in the index and the partial file. It could all easily be in the index as well if you didn't want to use a partial...I just assumed from your first question that that was what you were looking for. – kevindeleon Sep 26 '13 at 13:35
  • @heldrida Maybe I understand what you are saying now...I think what you are talking about could be accomplised using a directive and the compile function...have a look at this post and see if it is helpful http://stackoverflow.com/questions/14846836/insert-an-angular-js-template-string-inside-an-element – kevindeleon Sep 26 '13 at 13:45