Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/409.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript AngularJS:ui路由器href重写为ui sref_Javascript_Angularjs_Angular Ui Router - Fatal编程技术网

Javascript AngularJS:ui路由器href重写为ui sref

Javascript AngularJS:ui路由器href重写为ui sref,javascript,angularjs,angular-ui-router,Javascript,Angularjs,Angular Ui Router,我有一个CMS,它强制页面的URL具有某种模式。我们需要有条件地重写这些链接的HREF CMS将在页面上打印如下内容: <a href="/path/to/the/zoo/gorilla.html">Go</a> link.attr("href", "#/zoo/gorilla"); 如果我们自己写了这个链接,它看起来会像: <a ui-sref="zoo('gorilla')>Go</a> 我理解为什么这通常与ui路由器的理念背道而驰,但我

我有一个CMS,它强制页面的URL具有某种模式。我们需要有条件地重写这些链接的HREF

CMS将在页面上打印如下内容:

<a href="/path/to/the/zoo/gorilla.html">Go</a>
link.attr("href", "#/zoo/gorilla");
如果我们自己写了这个链接,它看起来会像:

<a ui-sref="zoo('gorilla')>Go</a>

我理解为什么这通常与ui路由器的理念背道而驰,但我希望能找到一种方法,在这个奇怪的情况下使用它。

我认为这会起作用,基本上是一个指令,当你点击它时,改变你指向哪个URL

module.directive('newHref', ['$location',function($location) {
    return function(scope, element, attrs) {
        element.bind('click', newHref);

        function newHref(event) {
            var hrefList = event.target.href.split("/");
            var parent = hrefList[hrefList.length-2];
            var child = hrefList[hrefList.length-1].split(".")[0];

            $location.path("/" + hrefList.slice(0, hrefList.length-2).join("/") + "/" + parent + "/" + child);
        }
    }
}]);
像这样使用它:

<a href="/path/to/the/zoo/gorilla.html" new-href>Go</a>

看起来像是进入了危险区域,但您可以创建“href”指令,该指令将自动替换
href
属性的值。不需要额外的属性,但这可能会使您的代码有点模棱两可

module
  .directive('href', function() {
    return function(scope, element, attrs) {
        var ngUrl; // convert CMS url to Angular URL somehow
        if(attrs.href === '/path/to/the/zoo/gorilla.html') {
            ngUrl = '#/zoo/gorilla';
        }

        element[0].href = ngUrl;
    };
});

我在问之前试过这个。更改href会将URL指向正确的散列,但状态无法识别此更改。@oooyaya更改了代码以允许路由器看到更改这就是我所做的。问题实际上是另外一个问题——使用名为子视图的ui路由器,并且必须在视图对象中以它们为目标。这就是为什么观点从未改变——我没有告诉它去哪里。我们做了类似的事情。也许这是一个错误的症状。href确实会更改,当我们单击它时,URL会更改为我们想要的内容,但视图不会更改。这意味着什么?它匹配管线和部分荷载,但从不显示。
module
  .directive('href', function() {
    return function(scope, element, attrs) {
        var ngUrl; // convert CMS url to Angular URL somehow
        if(attrs.href === '/path/to/the/zoo/gorilla.html') {
            ngUrl = '#/zoo/gorilla';
        }

        element[0].href = ngUrl;
    };
});