I'm developing a new proyect using angular and I have separated the: App (main module), controller and services in diferent files:
The responsabilities are:
indexApp.js
And them code is:
(function(indexApp) {
indexApp.App = {};
indexApp.Init = function() {
indexApp.App = angular.module("MainAppModule", ["MainControllerModule", "MainServiceModule"]);
};
}(window.indexApp = window.indexApp || {}));
indexController.js
And them code is:
(function (indexController) {
indexController.App = {};
indexController.MainController = function (service) {
var self = this;
var dataRetrieved = service.Login();
self.movie = {
title: dataRetrieved.Id,
director: dataRetrieved.Name,
date: dataRetrieved.LastName,
mpaa: "PG-13",
id: 0,
clickCommand: function () {
alert(self.movie.director);
},
loadData: function (id) {
console.log(id);
if (id !== 0) {
self.movie.title = "Titulo";
self.movie.director = "Director";
self.movie.date = "Mayo 16 de 2015";
self.movie.mpaa = "PG-25";
self.movie.id = id;
}
}
}
};
indexController.SetUrl = function (data) {
indexController.Redirect = data.Redirect;
};
indexController.Init = function () {
indexController.App = angular.module("MainControllerModule", []);
indexController.App.controller("MainController", indexController.MainController);
indexController.MainController.$inject = ["MainService"];
};
}(window.indexController = window.indexController || {}));
indexService.js
Them code is:
(function (indexService) {
indexService.App = {};
indexService.MainService = function () {
var self = this;
self.Login = function () {
return {
Id: 1,
Name: "Freddy",
LastName: "Castelblanco"
};
};
};
indexService.SetUrl = function (data) {
indexService.Login = data.Login;
};
indexService.Init = function () {
indexService.App = angular.module("MainServiceModule", []);
indexService.App.service("MainService", indexService.MainService);
};
}(window.indexService = window.indexService || {}));
At the end in my view I call the follow methods:
@using System.Web.Optimization
@{
Layout = "~/Views/Shared/_Layout.cshtml";
var id = 20;
}
<div ng-app="MainAppModule">
<div ng-controller="MainController as vm">
<div ng-init="vm.movie.loadData(@id)">
<div class="row">
<div class="col-md-12">{{vm.movie.title}}</div>
<input type="text" ng-model="vm.movie.title"><br>
</div>
<div class="row">
<div class="col-md-12">{{vm.movie.director}}</div>
</div>
<div class="row">
<div class="col-md-12">{{vm.movie.date}}</div>
</div>
<div class="row">
<div class="col-md-12">{{vm.movie.mpaa}}</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="button" ng-click="vm.movie.clickCommand()">Click me !!</button>
</div>
</div>
</div>
</div>
</div>
@section scripts
{
@Scripts.Render("~/bundles/index")
<script type="text/javascript">
indexApp.Init();
indexService.Init();
indexController.Init();
</script>
}
Is a correct way to use angular ?? Im using dependency injection.