【问题标题】:Angularjs: routes and controllers without templateURLs?Angularjs:没有模板URL的路由和控制器?
【发布时间】:2019-05-14 11:41:48
【问题描述】:

是否可以在没有templateURL的情况下使用Angularjs的路由和控制器?

例如,下面是我当前的路由、控制器和模板 url,

return app.config(['$routeProvider', function ($routeProvider) {
        $routeProvider
        .when("/",
        {
            templateUrl: "js/template/1.html",
            controller: "controller1"
        })
        .when("/list1",
        {
            templateUrl: "js/template/2.html",
            controller: "controller2"
        })
...

我的 html 中有 ng-view

<div ng-view></div>

我测试了没有templateUrl的路由,

return app.config(['$routeProvider', function ($routeProvider) {
            $routeProvider
            .when("/",
            {
                //templateUrl: "js/template/1.html",
                controller: "controller1"
            })
            .when("/view1",
            {
                //templateUrl: "js/template/2.html",
                controller: "controller2"
            })
    ...

结果 - 我的屏幕上没有显示任何内容。显然控制器不能再被触发了。

【问题讨论】:

  • 您真正的需求是什么?没有templateUrl怎么识别视图?
  • 我只想使用 Angular 的路由,而不是它的模板。我正在考虑将 JsViews 用于我的模板。我发现 Angular 的模板很丑,有很多 ng-xxx。

标签: angularjs


【解决方案1】:

使用带有空字符串的模板。

return app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
    .when("/",
    {
        template: "",
        controller: "controller1"
    })

【讨论】:

    【解决方案2】:

    Angular 使用 $routeProvider 定义将控制器附加到您的视图。如果您不想在 $routeProvider 配置中指定详细信息,则另一种选择是让应用程序登陆一个页面,使用类似 -

      .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html'
      })
        .when()
        .otherwise({
        redirectTo: '/'
      });
    

    });

    这样用户将登陆 main.html。现在在 main.html 上,您可以包含几个不同的 html 模板,例如 -

     <div ng-include src="'js/template/1.html'" ng-controller = 'Controller1'></div>
     <div ng-include src="'js/template/2.html'" ng-controller = 'Controller2'></div>
    

    注意上面使用/包含模板的语法 - "'&lt;&lt;Path&gt;&gt;'"

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      使用空字符串设置模板会出错并导致递归加载;我通过添加空 html 文件的链接来解决它。

       return app.config(['$routeProvider', function ($routeProvider) {
          $routeProvider
          .when("/",
          {
             template: "dummy.htm",
             controller: "controller1"
          })
      

      【讨论】:

        猜你喜欢
        • 2018-07-17
        • 1970-01-01
        • 2021-06-02
        • 1970-01-01
        • 1970-01-01
        • 2016-11-27
        • 2016-05-05
        • 1970-01-01
        • 2014-12-01
        相关资源
        最近更新 更多