Drumbeg
Drumbeg

Reputation: 1934

AngularJS coupling between view and controller

I have an AngularJS application in which I started off with my view files having the controller defined using the ng-controller directive.

myview.html

<div ng-controller="MyController">
   <ul>
     <li class="thumb" ng-repeat="item in items">
         <span profile ng-click="getItem(item.id)"></span>
     </li>      
   </ul> 
</div>

However, I am now using routing and my controller is defined as part of my routeProvider configuration.

myview.html

<div>
   <ul>
     <li class="thumb" ng-repeat="item in items">
         <span profile ng-click="getItem(item.id)"></span>
     </li>      
   </ul> 
</div>

router.js

.when('/homepage', {
   templateUrl: 'templates/myview.html',
   controller: 'MyController'
})

This works, but although at first it seemed like this was helping me to decouple my view from my controller, something feels off as I still have references to scope member variables in my view and these are tied to my controller.

Am I missing something here? What have I gained from specifying MyController in my routeProvider and not in my template?

Upvotes: 0

Views: 223

Answers (2)

Dipesh KC
Dipesh KC

Reputation: 3297

By defining the controller in your route, you can use the same view (template) in multiple controller (and pass different scoped data)

For example:

.when('/homepage', {
   templateUrl: 'templates/myview.html',
   controller: 'MyController'
})
.when('/list', {
   templateUrl: 'templates/myview.html',
   controller: 'MyListController'
})

Upvotes: 1

gogstad
gogstad

Reputation: 3739

For all practical purposes I don't believe you gained anything, except from conforming to the standard way of defining routes, views and controllers in AngularJS.

If we're thinking programming principles and MVC, your view now doesn't know anything about the controller, it is only dependent on the model (that'd be $scope in angular), which is fine and perfectly normal in a MVC-architecture.

Upvotes: 2

Related Questions