关于mvc,require.js和angular的童话故事.从来没有幸福过吗?

iLe*_*ing 7 requirejs asp.net-mvc-4 angularjs

所以.曾几何时,有四种神奇的生物:asp.net mvc,require.js和angular.一位聪明的巫师决定把它们放在同一个房子里,让asp.net的每一个视图都拥有自己的"代码隐藏"javascript文件;

首先他加入了 _Layout.cshtml

 <script  data-main="/main" src="~/Scripts/require.js"></script>
Run Code Online (Sandbox Code Playgroud)

然后他main.js在根中创建:

require.config({
    baseUrl: "/Scripts/",
    paths: {
        'jquery': 'jquery-1.9.1.min',
        'jquery-ui': 'jquery-ui-1.10.2.custom.min',
        'angular': 'angular.min',
        'ng-grid': 'ng-grid-2.0.2.debug'
    },
    shim: {
        'jquery': { exports: "$" },
        'underscore': { exports: "_" },
        'jquery-ui': ['jquery'],
    },
});
 // Standard Libs
require(['jquery','jquery-ui','underscore','angular']);
Run Code Online (Sandbox Code Playgroud)

没什么花哨和神奇的.但后来他创建了一个html助手:

public static MvcHtmlString RequireJs(this HtmlHelper helper)
{
    var controllerName = helper.ViewContext.RouteData.Values["Controller"].ToString(); // get the controllername 
    var viewName = Regex.Match((helper.ViewContext.View as RazorView).ViewPath, @"(?<=" + controllerName + @"\/)(.*)(?=\.cshtml)").Value; //get the ViewName - extract it from ViewPath by running regex - everything between controllerName +slash+.cshtml should be it;

// chek if file exists
    var filename = helper.ViewContext.RequestContext.HttpContext.Request.MapPath("/Scripts/views/" + controllerName.ToLower() + "-" +
                                                                  viewName.ToLower()+".js");
    if (File.Exists(filename))
    {
        return helper.RequireJs(@"views/" + controllerName.ToLower() + "-" + viewName.ToLower());   
    }
    return new MvcHtmlString("");
}

public static MvcHtmlString RequireJs(this HtmlHelper helper, string module)
{
    var require = new StringBuilder();
    require.AppendLine(" <script type=\"text/javascript\">");
    require.AppendLine("    require(['Scripts/ngcommon'], function() {");
    require.AppendLine("        require( [ \"" + module + "\"] );");
    require.AppendLine("    });");
    require.AppendLine(" </script>");

    return new MvcHtmlString(require.ToString());
}
Run Code Online (Sandbox Code Playgroud)

然后他可以_Layout.cshtml像这样使用它:

   @Html.RequireJs()
Run Code Online (Sandbox Code Playgroud)

如果你仔细聆听这个故事,你可能会注意到还有Scripts/ngcommon.js文件来手动引导angular.js并且有常用的角度指令和服务

require(['angular', 'jquery'], function() {
    angular.module("common",[]).directive('blabla', function() {
        return {
            restrict: 'A',
            scope: { value: "@blabla" },
            link: function(scope, element, attrs) {     }
        }
    });

    //manually bootstrap it to html body
    $(function(){
        angular.bootstrap(document.getElementsByTagName('body'), ["common"]);
    });
});
Run Code Online (Sandbox Code Playgroud)

这就是魔术:从现在开始,如果它是一个名为controllerName-viewName.js的\ Scripts\views中的javascript文件,home-index.js对于Home\Index.cshtml,它将由require.js自动拾取并加载.美不是吗?

然后魔术师想:如果我需要加载其他东西(比如ng-grid),并且不应该将某些东西注入到常见的角度模块中,因为并非所有页面都会使用它.当然,他总是可以手动将另一个模块引导到他需要的每个代码隐藏javascript中的页面元素中,但是他没有足够明智地找到问题的答案: 是否可以注入一些angular.js组件(如ng-grid) )直接进入控制器,而不将其作为app模块的一部分?

Dmi*_*eev 1

如果我正确理解魔术师的想法,那么可以通过将应用程序拆分为定义为组件集合的子模块来继续。

如果他为主模块设置依赖关系,则它将起作用,myApp例如:

var myApp = angular.module('myApp', ['Constants', 'Filters', 'Services', 'Directives', 'Controllers']);
myApp.Constants = angular.module('Constants', []);
myApp.Controllers = angular.module('Controllers', []);
myApp.Filters = angular.module('Filters', []);
myApp.Services = angular.module('Services', []);
myApp.Directives = angular.module('Directives', []);
Run Code Online (Sandbox Code Playgroud)

然后每个子模块:Services等等 - 可以使用单个组件进行扩展,例如:

myApp.Controllers.controller('MyController', function () {});
myApp.Services.factory('myService', function () {});
myApp.Directives.directive('myDirective', function () {});
myApp.Filters.filter('myFilter', []);
myApp.Constants.constant('myConstant', []);
Run Code Online (Sandbox Code Playgroud)

这样主应用程序模块会加载多个子模块,但每个结构并不重要。它可以在后端提供的每个页面上包含单独的控制器、服务、指令和过滤器 -魔术师只需要确保加载所有需要的依赖项即可。