0

I'm just learning Angular and have a very basic app set up. When rendering some data via the templateUrl property of a route, what would be the best way to include a sub-controller in the returned template? For example, including a "createOrEditItem" template at the bottom of a "viewItem" template so that the "createOrEditItem" can be reused on its own later?

I've tried putting a div in the template with its ng-controller attribute set to a controller name that I've defined at the app level, but it's not being activated. Should this be done with a directive instead to make it instantiate when the master controller has its contents set, or am I missing something more fundamental?

3
  • via the templateUrl property of a controller? AFAIK, controllers don't have templateUrls.. Commented May 11, 2017 at 13:20
  • maybe you are looking for a nested directives kind of thing.. check this plunker out for basic example of that Commented May 11, 2017 at 13:22
  • Thanks - I meant route not controller, and have edited the question! Commented May 11, 2017 at 13:47

2 Answers 2

1

yes, as mentioned in the later part of the question, you should be using a directive. Or, if using AngularJS >= v1.5, component should be the choice because they are pluggable and works well with nesting too.

Note that for the route also, you can directly use a component like this:

var myMod = angular.module('myMod', ['ngRoute']);
myMod.component('home', {
  template: '<h1>Home</h1><p>Hello, {{ $ctrl.user.name }} !</p>',
  //                    ^^^^ other components can be used here
  controller: function() {
    this.user = {name: 'world'};
  } 
});

myMod.config(function($routeProvider) {
  $routeProvider.when('/', {
    template: '<home></home>'
  });
});

Now, as the comment suggests, you can freely use other components in the template of home component.

Hope this helps a bit!

Sign up to request clarification or add additional context in comments.

2 Comments

This was absolutely what I wanted! Components seem like the way forward then. Minimal fussing with controllers and a good amount of reuse?
@tags2k correct! And, even from the forward compatibility (with Angular2 and 4) point of view, components are the way to go! Glad that helped a little..
0

A directive can be used.

Another option is to use a seperate view/route. So when you add a ui-view tag, you could define your view and route.

This is explained here: https://scotch.io/tutorials/angular-routing-using-ui-router

Comments

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.