There's no set place for models, so you can put them whereever you want. For example, you can embed logic in your controllers (/app/js/controllers.js
) or, even better, create services as explained in the Angular docs here. Services are in /app/js/services.js
I like to see things fail first, so we'll start from the other end.
In /app/partials/partial1.html
, add
card: {{ card | json }}}
This will print out the card as JSON. Refresh and nothing happens. Cool, I guess. This is because the card object doesn't exist in $scope for this controller.
We need to add card to the $scope. In the MyCtrl1 controller, add
$scope.card = { fake: 'card' };
Refresh to see this placeholder appear in our view.
We could create our "model" here, but, as described above, we're going to opt for using a service. This way, we can use it all over the place, not just in this controller.
- Add
'cardService'
to the list of myApp.controllers dependencies. - Add
cardService
to the arguments in the function. - Swap
{ face: 'card' }
out forcardService
.
You should end up with something like this.
.controller('MyCtrl1', [
// dependencies
'$scope',
'cardService',
function ($scope, cardService) {
$scope.card = cardService;
}
])
Refresh and you'll see Angular complain.
Unknown provider: cardServiceProvider <- cardService
In /app/js/services.js
, add a definition for our service. We do this with the service
method. Yeah, it's not what you would normally think of as a service, it's just what Angular uses to define dependencies.
.service(
// service name
'cardService',
// provider function, responsible for creating instances
function () {
return { isCard: true };
}
)
Now when we view our page, we see the data from our service, injected into our model, and plugged into the view.