3

this is a fundamental question about MVC (in particular using AngularJS) and I've found similar questions here, but not the exact same problem:

Could the view call a function of the model, or should it only call functions of the controller?

Here's the example:

In my Model there's a function to delete items of a collection, like this:

function deleteItems(searchExpression) { ... }

Now my Controller has an instance of my model including that function, like this:

$scope.data = queryModelFactory.getModel();

I now want to call that funciton when the user clicks a certain element in the HTML page:

<div ng-click="data.deleteItems('blabla')">Remove Items</div>

Is that legit? Or would it be better to implement a function in the controller that is passing through the delete request to my model like I'd do in a classical layer architecture? Like this:

function deleteItems(searchExpression) {
    $scope.data.deleteItems(searchExpression);
}
3

The Model-View-Controller pattern divides the application into three interconnected parts namely the model, the view and the controller.

The central component of MVC, the model, captures the behavior of the application in terms of its problem domain, independent of the user interface. The model directly manages the data, logic and rules of the application. A view can be any output representation of information, such as a chart or a diagram. The third part, the controller, accepts input and converts it to commands for the model or view.

The view should not directly interact with the model but rather delegate the events (e.g. user input) to the controller. In your case, the latter option you presented implements the pattern correctly.

  • 3
    At best, this shows an understanding of just one form of the MVC pattern. At worst, it shows a fundamental misunderstanding of the pattern. What you describe is the "passive" pattern. There's another variant of the pattern where the model gets directly bound to the view. – RubberDuck Oct 11 '15 at 2:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.