【问题标题】:AngularJS and $stateProvider : How to keep the context while replacing templateUrl by templateUrl?AngularJS 和 $stateProvider:如何在用 templateUrl 替换 templateUrl 时保留上下文?
【发布时间】:2014-11-19 21:46:36
【问题描述】:

我正在使用 $stateProvider 和这样的路由表(简化版):

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('app', {
      url: "/app",
      abstract: true,
      templateUrl:'menu.html',
      controller: 'AppCtrl'
    })

    .state('app.home', {
      url: "/home",
      views: {
        'menuContent' :{
          templateUrl:'home.html'
        }
      }
    })

  $urlRouterProvider.otherwise('/app/home');
});

此方案运行良好,但在将项目移植到另一个框架时,通过 url 加载模板不再是一种选择。因此,我不得不重构我的代码,将 templateUrl 属性替换为 template 属性。

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('app', {
      url: "/app",
      abstract: true,
      template:UiRouter.template('menu.html'), // UiRouter now provides the menu.html template content
      controller: 'AppCtrl'
    })

    .state('app.home', {
      url: "/home",
      views: {
        'menuContent' :{
          template:UiRouter.template('home.html'), // UiRouter now provides the home.html template content
        }
      }
    })

  $urlRouterProvider.otherwise('/app/home');
});

不幸的是,以这种方式加载模板似乎让我失去了范围。为了解释,我在“menu.html”中有指令,例如 ion-Nav-Bar 提供一个控制器 (ionNavBar),在 home.html 模板中的另一个指令中是强制性的。使用 templateUrl 属性效果很好,但通过模板导入似乎 isolate the scope

我应该为模板提供一个控制器吗?或者简单地说……那我该如何扩大范围?

【问题讨论】:

    标签: angularjs angularjs-scope angular-ui-router


    【解决方案1】:

    好的,问题来自应用程序启动太早,即在我的框架准备好正确提供模板之前,因此 AngularJS 能够将所有内容编译在一起。

    因此,我将引导从 ng-app 指令替换为手动指令,即

    Meteor.startup(function ()
    {    
      angular.bootstrap(document, ['myApp']);
    });
    

    是的,框架是流星......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-10
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多