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!

1
  • you want add another html file in 1st html. Commented Sep 24, 2013 at 15:58

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for looking! I guess this is a bad practice, but I'm trying to avoid having to write some html in my controller.
@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.
@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 stackoverflow.com/questions/14846836/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.