Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply Angular Controller to a Template

So, I'm not sure what it is I'm asking, but I want to achieve this:

Index.html:

<div ng-view>

</div>
<script>
    angular.module('myApp', ['ngRoute'])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/', { controller: "HomeController", templateUrl: '/Partials/Home/Dashboard.html' });

        $routeProvider.otherwise({ redirectTo: '/' });
    }]);
</script>

Home/Dashboard.html:

<h2 class="page-header">{{welcome}}</h2>

<!-- Insert my reusable component here -->

My reusable component would reside in MyComponent/Component.html and have the controller myApp.component.controller associated with it.

So effectively I want to drop in the resuable component into the page and bind it to my controller. So I got as far as having this:

.directive('MyComponent', function() {
    return {
      restrict: 'E',
      scope: {

      },
      templateUrl: '/MyComponent/Component.html'
    };
  });

So how do I now bind my controller to it? Do I do this:

.directive('MyComponent', function() {
    return {
      restrict: 'E',
      resolve: function () {
        return /* resolve myApp.component.controller */;
      },
      templateUrl: '/MyComponent/Component.html'
    };
  });
like image 926
Callum Linington Avatar asked Dec 05 '25 19:12

Callum Linington


1 Answers

When a directive requires a controller, it receives that controller as the fourth argument of its link function.

.directive('MyComponent', function() {
    return {
      restrict: 'E',
      controller: 'MyController', // attach it.
      require: ['MyController','^ngModel'],    // required in link function
      templateUrl: '/MyComponent/Component.html',
      link: function(scope, element, attrs, controllers) {
         var MyController = controllers[0];
         var ngModelCtlr = controllers[1];
         ///...
      }
    };
  });

The ^ prefix means that this directive searches for the controller on its parents (without the ^ prefix, the directive would look for the controller on just its own element).

Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.

like image 67
rnrneverdies Avatar answered Dec 08 '25 07:12

rnrneverdies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!