Angularjs将ui-router controller $ scope传递给数据

时间:2015-03-03 16:53:07

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

我想根据pageTitle从ui-router传递$stateParams数据,然后使用指令更新页面标题

ui-router示例:

.state('index.something.detail', {
        url: '/{type}/{else}',
        views: {
            '': {
                templateUrl: 'tempalte.html',
                controller: function($scope, $stateParams) {
                    if ($stateParams.type == "param") {
                        $scope.title = "param";
                    }
                }
            }
        },
        data: {
            pageTitle: 'Something {{title}}', //NOT WORKING
        },
        ncyBreadcrumb: {
            label: 'Sometgin {{title}}', //IT WORKS
            parent: 'index.something'
        }
    })

指令示例:

function pageTitle($rootScope, $timeout) {
    return {
        link: function(scope, element) {
            var listener = function(event, toState, toParams, fromState, fromParams) {
                // Default title - load on Dashboard 1
                var title = 'APP';
                // Create your own title pattern
                if (toState.data && toState.data.pageTitle) title = 'APP | ' + toState.data.pageTitle;
                $timeout(function() {
                    element.text(title);
                });
            };
            $rootScope.$on('$stateChangeStart', listener);
        }
    }
};

angular-breadcrumb传递数据确定

  

Something param

但是在pageTitle指令中我得到了

  

Something {{title}}

如何通过ui-router状态的$ scope?

谢谢!

1 个答案:

答案 0 :(得分:0)

我们无法通过data设置传递此内容。原因是,data {}中的字符串参数只是一个字符串,而不是视图模板。我们需要编译它并传递一个范围。

但是有更好的解决方案。检查一下working example 让我们像这样拥有index.html:

<H1><ui-view name="title" /></H1>

<ul>
  <li><a ui-sref="parent">parent</a>
  <li><a ui-sref="parent.child">parent.child</a>
</ul>

<div ui-view=""></div>

我们的州现在可以将东西注入两个地方:

.state('state name', {
  ...
  views : {
    "" : {
      // default view
    }
    "title" : {
      template : "parent is setting title inside of index.html"
    }
  }
})

选中此here in action

另外,请在此处观察UI-Router默认示例应用程序(执行相同的操作):

http://angular-ui.github.io/ui-router/sample/#/

代码中最重要的部分是Contact state def,有一个小代码段:

// You can have unlimited children within a state. Here is a second child
// state within the 'contacts' parent state.
.state('contacts.detail', {    
    ...
     views: {
      // So this one is targeting the unnamed view within the parent state's template.
      '': {
       ...
      },
      // This one is targeting the ui-view="hint" within the unnamed root, aka index.html.
       // This shows off how you could populate *any* view within *any* ancestor state.
      'hint@': {
        template: 'This is contacts.detail populating the "hint" ui-view'
      },
      // This one is targeting the ui-view="menuTip" within the parent state's template.
      'menuTip': {