代码之家  ›  专栏  ›  技术社区  ›  N.Car

AngularJS-带有ng点击的ui路由无法正常工作

  •  0
  • N.Car  · 技术社区  · 7 年前

    我用用户界面路由器创建了一些路由,我发现这件事很奇怪。

    我有这个路线配置

        .state('chapter_route', {
        url: '/book/:chap',
        templateUrl: "views/chapter.html",
        params: { chap: null}
    })
    

    <a ui-sref="chapter_route({ chap: getChapter.title})">CHAPTER:</a>
    

        <div class="panel panel-default">
                            <div class="panel-body">
                                <p>{{getChapter.title}}</p>
                                {{getChapter.content}}
                            </div>
        </div>
    ......
    ......
            <div class="panel panel-default" data-ng-repeat="cha in allChapters">
                <div class="panel-body">
                    <a ui-sref="chapter_route({ chap: cha.title})" ng-click="changeChapter(chap)">{{cha.title}}</a> {{cha.content | limitTo: 100}}.
                    <button ng-click="changeChapter(article)">PRESS ME </button>
                </div>
            </div>
    

    正如你所见,我还有一个 <a>

    getChapter看起来像:

    $scope.allChapters = [
        {
            title: "title 1",
            chapter: "the whole chapter goes here"
        },
        {
            title: "title 2",
            chapter: "the whole chapter 2 goes here"
        },
        {
            title: "title 3",
            chapter: "the whole chapter 3 goes here"
        }
        ];
    
    $scope.getChapter = $scope.allChapters[0];
    

    $scope.changeChapter = function(chap){
        $scope.getChapter = chap;
        console.log($scope.getChapter);
    };
    

    下面是真正发生的事情: 我从展示第一章开始,并为接下来的所有章节创建链接。如果我点击 < 标记它使用ng click更改getChapter的值,并在控制台上完美地打印它,但除非我再次单击它,否则它不会更改本章的ui视图。我可以看到ui视图在几秒钟内发生了变化,但它并没有保持不变,它很快加载了第一章的ui视图。但如果我再次点击,它会显示我点击的章节。所以,我需要点击两次,它才能改变,这很奇怪。

    但是,如果我决定单击“PRESS ME”(按我)按钮,它将直接切换到ui视图中的下一章。 我希望能够点击 <a>

    你知道是什么导致了这个奇怪的错误吗?

    编辑:

    https://plnkr.co/edit/D6f9Q3fhL294DukEZFOz?p=preview

    我在我们正在讨论的问题中添加了一个简单的plunker,这样你可以更好地了解我在说什么。

    2 回复  |  直到 7 年前
        1
  •  1
  •   vpsingh016    7 年前

    问题在于控制器代码 $scope.getChapter = $scope.allChapters[0]; 在这里,对于所有情况,您都是使用第一章硬编码当前章节,因此在所有情况下,它只会呈现相同的内容。 if (!$stateParams.chap) { $scope.selectedChapter = $scope.allChapters[0]; } . 它会解决你的问题。 Updated Plunker with Fix

        2
  •  1
  •   chirag satapara    7 年前

    Check this plunker for your working example

    你必须使用 $state.go 为了这个。

    $scope.changeChapter = function(chap){
        $scope.getChapter = chap;
        $state.go('chapter_route', {chap: chap});
        console.log($scope.getChapter);
    };
    

    $state