Skip to main content
2 de 5
se añadieron 137 caracteres en el cuerpo

SPA Angular Js + MVC .NEt

Estoy iniciando con el tema de Single Page Applications con MVC de .Net , y se ha vuelto complicado resolver las dependencias , he tomado el ejemplo de la pagina http://www.codemag.com/article/1605081 y todo va bien , hasta que trado de usar componentes de ui.bootstrap , el punto es que los modules que estan relacionados con el commonModule , no pueden acceder a dicha dependencia Link de descarga del proyecto SPA MVC + AngularJs

CODIGO del App.js principal:

var commonModule = angular.module('common', ['ngRoute', 'ngAnimate', 'ngSanitize', 'ui.bootstrap']);
var mainModule = angular.module('main', ['common']);

commonModule.factory('viewModelHelper',
    function ($http, $q, $window, $location) {
        return MyApp.viewModelHelper(
            $http, $q, $window, $location);
    });

commonModule.factory('validator', function () { return valJs.validator(); });

mainModule.controller("indexViewModel", function (
    $scope, $http, $q, $routeParams, $window,
    $location, viewModelHelper) {

    var self = this;

    $scope.topic =
        "Integrating ASP.NET MVC and AngularJS";
    $scope.author = "";
});

(function (myApp) {
    var viewModelHelper = function (
        $http, $q, $window, $location) {

        var self = this;

        self.modelIsValid = true;
        self.modelErrors = [];

        self.resetModelErrors = function () {
            self.modelErrors = [];
            self.modelIsValid = true;
        }

        self.apiGet = function (uri, data, success, failure, always) {
            self.modelIsValid = true;
            $http.get(MyApp.rootPath + uri, data)
                .then(function (result) {
                    success(result);
                    if (always != null)
                        always();
                }, function (result) {
                    if (failure != null) {
                        failure(result);
                    }
                    else {
                        var errorMessage = result.status + ':' + result.statusText;
                        if (result.data != null) {
                            if (result.data.Message != null)
                                errorMessage += ' - ' + result.data.Message;
                            if (result.data.ExceptionMessage != null)
                                errorMessage += ' - ' + result.data.ExceptionMessage;
                        }
                        self.modelErrors = [errorMessage];
                        self.modelIsValid = false;
                    }
                    if (always != null)
                        always();
                });
        }

        self.apiPost = function (uri, data, success, failure, always) {
            self.modelIsValid = true;
            $http.post(MyApp.rootPath + uri, data)
                .then(function (result) {
                    success(result);
                    if (always != null)
                        always();
                }, function (result) {
                    if (failure != null) {
                        failure(result);
                    }
                    else {
                        var errorMessage = result.status + ':' + result.statusText;
                        if (result.data != null) {
                            if (result.data.Message != null)
                                errorMessage += ' - ' + result.data.Message;
                            if (result.data.ExceptionMessage != null)
                                errorMessage += ' - ' + result.data.ExceptionMessage;
                        }
                    }
                    if (always != null)
                        always();
                });
        }

        self.goBack = function () {
            $window.history.back();
        }

        self.navigateTo = function (path, params) {
            if (params == null)
                $location.path(MyApp.rootPath + path);
            else
                $location.path(MyApp.rootPath + path).search(params);
        }

        self.refreshPage = function (path) {
            $window.location.href = MyApp.rootPath + path;
        }

        self.clone = function (obj) {
            return JSON.parse(JSON.stringify(obj))
        }

        self.querystring = function (param) {
            if ($location.search != null)
                return $location.search()[param];
            else
                return null;
        }

        self.resetQueryParams = function () {
            $location.url($location.path());
        }

        return this;
    };
    myApp.viewModelHelper = viewModelHelper;
}(window.MyApp));

CODIGO del App.js para Custumer:

var customerModule = angular.module('customer', ['common']);

customerModule.config(function ($routeProvider,
                                $locationProvider) {
    $routeProvider.when('/customer', {
        templateUrl: '/App/Customer/Views/CustomerHomeView.html',
        controller: 'customerHomeViewModel'
    });
    $routeProvider.when('/customer/list', {
        templateUrl: '/App/Customer/Views/CustomerListView.html',
        controller: 'customerListViewModel'
    });
    $routeProvider.when('/customer/show/:customerId', {
        templateUrl: '/App/Customer/Views/CustomerView.html',
        controller: 'customerViewModel'
    });
    $routeProvider.otherwise({
        redirectTo: '/customer'
    });
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });
});

customerModule.factory('customerService',
    function ($http, $location, viewModelHelper) {
        return MyApp.customerService($http,
            $location, viewModelHelper);
    });

(function (myApp) {
    var customerService = function ($http, $location,
        viewModelHelper) {

        var self = this;

        self.customerId = 0;

        return this;
    };
    myApp.customerService = customerService;
}(window.MyApp));

CODIGO del RootViewModel (o controler para customer):

customerModule.controller("rootViewModel", function ($scope,$window,customerService, $http, viewModelHelper) {

    // This is the parent controller/viewmodel for 'customerModule' and its $scope is accesible
    // down controllers set by the routing engine. This controller is bound to the Customer.cshtml in the
    // Home view-folder.

    $scope.viewModelHelper = viewModelHelper;
    $scope.customerService = customerService;

    $scope.flags = { shownFromList: false };

    var initialize = function () {
        $scope.pageHeading = "Customer Section";

    }

    $scope.tabs = [
   { title: 'Dynamic Title 1', content: 'Dynamic content 37' },
   { title: 'Dynamic Title 2', content: 'Dynamic content 2', disabled: true }
    ];

    $scope.alertMe = function () {
        setTimeout(function () {
            $window.alert('You\'ve selected the alert tab!');
        });
    };

    $scope.model = {
        name: 'Tabs'
    };
    
    initialize();
});

Codigo _Layout.cshtml:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" 
              content="width=device-width, initial-scale=1.0">
        <title>@ViewBag.Title - ASP.NET MVC with Angular JS</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body data-ng-app="main">
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" 
                            data-toggle="collapse" 
                            data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    @Html.ActionLink("ASP.NET MVC/Angular JS", 
                        "Index", "Home",
                        new { area = "" }, 
                        new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Customers",
                                             "Customer",
                                             "Home")</li>
                        <li>@Html.ActionLink("Products", 
                                             "Product", 
                                             "Home")</li>
                        <li>@Html.ActionLink("Orders",
                                             "Order",
                                             "Home")</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="container body-content">
            @RenderBody()
            <hr />
            <footer>
                <p>&copy; @DateTime.Now.Year</p>
            </footer>
        </div>

        @Scripts.Render("~/bundles/angular")
        <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.2.0.js"></script>
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
       
        <script type="text/javascript">
            window.MyApp = {};
            MyApp.rootPath = '@Url.Content("~")';
        </script>
        <script src="~/App/Validator.js"></script>
        <script src="~/App/App.js"></script>        
        @RenderSection("scripts", required: false)
        <script type="text/javascript">
            @RenderSection("jsCode", required: false)
        </script>
    </body>
</html>

y finalmente este es el codigo de Customer.cshtml , donde en un inicio pensaba mostrar algunos tabs con formularios de captura de datos . pero por algun motivo no puedo utilizar los tabs , la dependencia al ser cargada en el commonModule de bootstrap se supondria que deberia estar disponible.

@{
    ViewBag.Title = "Customers";
}
@section scripts {
    <script src="~/App/Customer/App.js"></script>
    <script src="~/App/Customer/ViewModels/RootViewModel.js"></script>
    <script src="~/App/Customer/ViewModels/CustomerHomeViewModel.js"></script>
    <script src="~/App/Customer/ViewModels/CustomerListViewModel.js"></script>
    <script src="~/App/Customer/ViewModels/CustomerViewModel.js"></script>
}
@section jsCode {
    angular.bootstrap(document.getElementById("customer"), ['customer']);
}

<div ng-non-bindable>

   <div id="customer" data-ng-controller="rootViewModel">
        <h2>{{ pageHeading }}</h2>
        <div class="row">

            <p>Select a tab by setting active binding to true:</p>
            <uib-tabset active="active">
                <uib-tab index="0" heading="Static title">Static content</uib-tab>
                <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}" disable="tab.disabled">
                    {{tab.content}}
                </uib-tab>
                <uib-tab index="3" select="alertMe()">
                    <uib-tab-heading>
                        <i class="glyphicon glyphicon-bell"></i> Alert!
                    </uib-tab-heading>
                    I've got an HTML heading, and a select callback. Pretty cool!
                </uib-tab>
            </uib-tabset>
            <hr />
           
        <hr />*@
        <div ng-view></div>
        <hr />
        <div>
            <a href="/product" target="_self">Products</a>
            &nbsp;|&nbsp;
            <a href="/order" target="_self">Orders</a>
        </div>


    </div>
</div>

Agradezco de antemano cualquier ayuda.