【问题标题】:How to set a variable according to ui-view?如何根据ui-view设置变量?
【发布时间】:2017-05-31 13:56:24
【问题描述】:

我在 angularjs 的 ui 视图上方有一个 pageheader 模板。我想指定一个变量showDropdown 来控制pageheader 中某些DOM 的出现。 showDropdown 变量特定于 ui-view。例如,showDropdown 在第一个视图中是 true,在第二个视图中是 false。我怎样才能让它根据ui-view改变?

我尝试在stateProvideronEnter()中设置变量,但没有影响。

HTML,

<pageheader></pageheader>
<br />
<div class="container">
  <div class="row"><div class="col-xs-12 no-padding"><div ui-view="view"></div></div></div>
</div>

pageherder 模板,

<div>
......
</div>
<div ng-if="showDropdown">
  ........
</div>

JS,

.config(function($stateProvider)
{
    $stateProvider
        .state('printer',
        {
            url: "/printer",
            views:
            {
                "view":
                {
                    templateUrl: "/static/tpls/cloud/app/printer.php"
                }
            },
            onEnter: function(){
                showDropdown = false;
            }
        })
        .state('control',
        {
            url: "/control",
            views:
            {
                "view":
                {
                    templateUrl: "/static/tpls/cloud/app/control.php"
                }
            }
        })
})

编辑Pengyy's answer

    app.controller('CloudController', ['$scope', '$http', '$interval', '$timeout', 'optSev', '$state', '$rootScope', function($scope, $http, $interval, $timeout, optSev, $state, $rootScope)
    {
        var search  = window.location.search.substring(1);
        var paras = search.split("&");
        paras = paras[0].split("=");
        pid = paras[1];
        $scope.pid = pid;
        $scope.active = {};
        $scope.idle = true;
        $scope.active.status = {};
        $scope.active.state = {};
        $scope.showDropdown = $state.current.showDropdown;
        //$scope.showDropdown = $rootScope.showDropdown;
//console.log($scope.showDropdown);
console.log($state);
console.log($state.current);
//console.log($state.$current);
.....

很累,

console.log($state); // it shows the showDropdown

console.log($state.current); // the showDropdown is missed.


【问题讨论】:

标签: javascript html angularjs angular-ui-router


【解决方案1】:

您可以简单地将showDropdown 添加到您的状态配置中,如下所示:

$stateProvider
    .state('printer',
    {
      url: "/printer",
      views:
      {
        "view":
        {
          templateUrl: "/static/tpls/cloud/app/printer.php"
        }
      },
      showDropdown: false
    })

并在您的控制器中通过$state.current.showDropdown 检索它。


演示plunker

【讨论】:

  • 我添加了这一行showDropdown: false;,但得到SyntaxError: missing } after property list
  • @KrisRoofe 真的很抱歉,你必须删除;:P
  • 是的,当移动;时,没有这样的错误。我正在测试它现在是否有效。
  • 在控制器中,我可以在$state 变量中看到“showDropdown”,但在$state.current 中看不到。我在我的问题中添加了奇怪的问题。
  • @KrisRoofe 我认为这不是 ui-view 的正确用法,但您仍然可以使用 $state.get('printer').showDropdown 处理它。 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
相关资源
最近更新 更多