javascript Angular-UI-Router:ui-sref 不使用参数构建 href

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28574053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:12:02  来源:igfitidea点击:

Angular-UI-Router: ui-sref not building href with parameters

javascriptangularjsangular-ui-router

提问by Schleichermann

I have an HTML page, once loaded in the user's browser the 'list' state is activated and the 'list' partial is pulled by Angular and populated with a list of servers.

我有一个 HTML 页面,一旦加载到用户的浏览器中,“列表”状态就会被激活,“列表”部分由 Angular 提取并填充服务器列表。

Each server has a 'details' link that specifies the 'details' state for that server.

每个服务器都有一个“详细信息”链接,用于指定该服务器的“详细信息”状态。

<td><a ui-sref="details({ serverName: '{{server.name}}' })">Details</a></td>

When rendered the 'ui-sref' generates the expected 'href' url based on the route and its optional parameters.

渲染时,'ui-sref' 会根据路由及其可选参数生成预期的 'href' url。

<a ui-sref="details({ serverName: 'SLCMedia' })" href="#/details/SLCMedia">Details</a>

When clicked it works as expected and the 'details' partial is pulled and in the controller assigned to that state pulls the server with the name specified.

单击它时,它按预期工作,并拉取“详细信息”部分,并在分配给该状态的控制器中拉取指定名称的服务器。

The issue I am running into is the fact that once the 'details' partial is loaded, it too has a 'ui-sref' to an 'edit' state.

我遇到的问题是,一旦加载了“详细信息”部分,它也会有一个“ui-sref”到“编辑”状态。

   <a ui-sref="edit({ serverName: '{{server.name}}' })">
        <button class="btn btn-lg btn-labeled btn-primary">
            <span class="btn-label icon fa fa-edit"></span>
            Edit
        </button>
    </a>

But when this partial is loaded the 'ui-sref' is not generating the correct 'href' url.

但是当加载这个部分时,'ui-sref' 没有生成正确的 'href' url。

   <a ui-sref="edit({ serverName: 'SLCMedia' })" href="#/edit/">
        <button class="btn btn-lg btn-labeled btn-primary">
            <span class="btn-label icon fa fa-edit"></span>
            Edit
        </button>
    </a>

As you can see the 'href' url is '#/edit/' not '#/edit/SLCMedia' as would be expected. It's got to be something simple that I am missing. Does the change of state have something to do with it?

正如您所看到的,'href' url 是 '#/edit/' 而不是 '#/edit/SLCMedia',正如预期的那样。这一定是我遗漏的一些简单的东西。状态的变化与它有关吗?

Here are all of defined 'states' for the page.

这是页面的所有定义的“状态”。

// Create the Angular App to rule the Server Management Page
var serverApp = angular.module('serverApp', [
    'ui.router',
    'serverControllers',
    'utilitiesService'
]);

serverApp.config(function ($stateProvider, $urlRouterProvider) {
    // For any unmatched url, redirect to /state1
    $urlRouterProvider.otherwise("/list");

    // Now set up the states
    $stateProvider
        .state('list', {
            url: '/list',
            templateUrl: '/views/pages/servers/list.html',
            controller: 'serverListCtrl'
        })
        .state('details', {
            url: '/details/:serverName',
            templateUrl: '/views/pages/servers/details.html',
            controller: 'serverDetailsCtrl'
        })
        .state('create', {
            url: '/create',
            templateUrl: '/views/pages/servers/create.html'
        })
        .state('edit', {
            url: '/edit/:serverName',
            templateUrl: '/views/pages/servers/edit.html',
            controller: 'serverEditCtrl'
        })
});

Here are my controllers

这是我的控制器

var serverControllers = angular.module('serverControllers', ['utilitiesService']);

serverControllers.controller('serverListCtrl', function ($scope, $http) {
    $http.get('/servers/getList').success(function (data) {
        $scope.serverList = data;
    });
});

serverControllers.controller('serverDetailsCtrl', function ($scope, $stateParams, $http) {
    var serverName = $stateParams.serverName;

    $http.get('/servers/getServerByName/' + serverName).success(function (data) {
        $scope.server = data;
    });
});

serverControllers.controller('serverEditCtrl', function ($scope, $stateParams, $http, $state, showAlertMessage) {
    var serverName = $stateParams.serverName;

    $http.get('/servers/getServerByName/' + serverName).success(function (data) {
        $scope.server = data;
    });

    $scope.server.submitForm = function (item, event) {
        console.log("--> Submitting Server Update");

        //TIMDO: Verify all required fields have been included

        var responsePromise = $http.post("/servers/postEdit", $scope.server, {});
        responsePromise.success(function(dataFromServer, status, headers, config) {
            showAlertMessage({
                type: 'success',
                title: 'Success',
                message: 'Server information updated'
            });

            $state.go('clear');
        });
        responsePromise.error(function(data, status, headers, config) {
            showAlertMessage({
                type: 'error',
                title: 'Success',
                message: 'Server information updated'
            });
        });
    }
});

回答by Jason Swett

Hmm, I'm probably misunderstanding your issue but I see at least one obvious difference between the look of your code and the look of mine.

嗯,我可能误解了您的问题,但我发现您的代码外观和我的外观之间至少有一个明显的区别。

My angular-ui-router links look like this:

我的 angular-ui-router 链接如下所示:

<a ui-sref="reps-show({ id: rep.id })">{{rep.name}}</a>

The difference is the absence of braces around rep.id. So I wonder if changing this

不同之处在于周围没有大括号rep.id。所以我想知道是否改变这个

<td><a ui-sref="details({ serverName: '{{server.name}}' })">Details</a></td>

to this

对此

<td><a ui-sref="details({ serverName: server.name })">Details</a></td>

might do something for you.

可能会为你做些什么。

That's probably not it but that's the first thing that came to mind for me.

这可能不是它,但这是我想到的第一件事。

回答by Radim K?hler

I created simplified, but working version here. Because there is nothing obviously wrong. This example should at least help you to assure that:

我在这里创建了简化但有效的版本。因为没有什么明显的错误。这个例子至少应该可以帮助你确保:

All you are trying to do is supposed to be working.

您所做的一切都应该是有效的。

Here are states:

以下是状态:

// States
$stateProvider
      .state('list', { 
          url: "/list",
          templateUrl: 'tpl.list.html',
          controller: 'serverListCtrl',
      })
      .state('edit', {
        url: '/edit/:serverName',
        templateUrl: 'tpl.html',
        controller: 'serverEditCtrl'
    })

Here controller of a list loading data

这里是一个列表加载数据的控制器

.controller('serverListCtrl', ['$scope', '$http', function ($scope, $http) {
    $http.get('server.json').success(function (data) {
        $scope.serverList = data;
    });
}])

(server.json) - example of data

(server.json) - 数据示例

[
  {"name":"abc"},
  {"name":"def"},
  {"name":"xyz"}
]

And the same template:

和相同的模板:

<li ng-repeat="server in serverList">
    <a ui-sref="edit({ serverName: '{{server.name}}' })">
        <button class="btn btn-lg btn-labeled btn-primary">
            <span class="btn-label icon fa fa-edit"></span>
            Edit {{server.name}}
        </button>
    </a>
</li>

All is working as expected. Check it here.

一切都按预期工作。在这里检查。

回答by Volte

I want to contribute with another datapoint in-case some other folks arrive here with a similar question, as I did.

我想提供另一个数据点,以防其他人像我一样提出类似的问题。

I was using the non-curly-brace version in my app, and it wasn't working. My specifics involve the InfoWindow in Google Maps. I believe there is a rendering order "issue" such that the data required for the ui-sref link doesn't exist, and when it does finally exist, it's never "re-rendered".

我在我的应用程序中使用了非大括号版本,但它不起作用。我的细节涉及Google Maps 中的 InfoWindow 。我相信存在一个渲染顺序“问题”,以至于 ui-sref 链接所需的数据不存在,并且当它最终存在时,它永远不会“重新渲染”。

Original (non-working) version:

原始(非工作)版本:

%h3
  {{window_info.data.user.name || "Mystery Person"}}
%a.fa.fa-info-circle{ ui: { sref: 'users.show({id: window_info.data.user.id })' } }
%pre {{window_info.data.user.id | json}}

Working version:

工作版本:

%h3
  {{window_info.data.user.name || "Mystery Person"}}
%a.fa.fa-info-circle{ ui: { sref: "users.show({id: '{{ window_info.data.user.id }}' })" } }
%pre {{window_info.data.user.id | json}}

I placed the %pretag with the info to prove to myself that the datum was in-fact present (at least ultimately/eventually), but even still the original code for the link was not working. I adjusted my code to use the interpolated curly-brace version as per the OPs situation and it worked.

我在%pre标签上放置了信息以向自己证明数据实际上存在(至少最终/最终),但即使链接的原始代码仍然无法正常工作。我根据 OP 的情况调整了我的代码以使用插入的花括号版本并且它有效。

Conclusion:Your solution could depend on the way in which the parent component is handling rendering. Google Mapsin this case is fairly notorious for being "funky" (technical term) with rendering, particularly in Angu-land.

结论:您的解决方案可能取决于父组件处理渲染的方式。在这种情况下,谷歌地图因渲染“时髦”(技术术语)而臭名昭著,尤其是在安古地区。