punkbit
punkbit

Reputation: 7707

AngularJS: Load view from Controller?

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!

Upvotes: 3

Views: 6736

Answers (1)

kevindeleon
kevindeleon

Reputation: 1924

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>

Upvotes: 2

Related Questions