【问题标题】:How to change the path from custom directive? Angular如何从自定义指令更改路径?角
【发布时间】:2016-12-13 15:27:31
【问题描述】:

我有以下指令,它是一个按钮,并在单击按钮时尝试更改路径但没有任何反应。

app.directive('searchAgainButton', function ($location) {
    return {
        template: '<button class="searchAgainButton"><i class="fa fa-search" aria-hidden="true"></i><span> Search Again</span></button>',
        link: function (scop, element, attrs) {
            element.on('click', function () {
                 $location.path('/index')
            })
         }
     }
});

【问题讨论】:

  • 你试过在作用域上使用 $apply 吗?
  • @AnirudhMangalvedhekar 不,我应该把 $location.path('/index') 放在下面吗?
  • $location 未声明为依赖项。应该是app.directive('searchAgainButton', ['$location', function ($location) { // code here }]);
  • 试过 element.bind() 而不是 element.on() ?
  • element.bind 已弃用..它更好地使用

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


【解决方案1】:

element 没有指向按钮。试试这个

    var app = angular.module('myApp', []);

    app.directive('searchAgainButton', function ($location) {
        return {
                restrict:"AE",
            template: '<button ng-click="changePath()" class="searchAgainButton"><i class="fa fa-search" aria-hidden="true"></i><span> Search Again</span></button>',
            link: function (scope, element, attrs) {
                scope.changePath = function(){
                     $location.path('/index')
                }
             }
         }
    });

//html
<div ng-app="myApp">
  <div search-again-button></div>
</div>

FIDDLE EXAMPLE

【讨论】:

    猜你喜欢
    • 2016-09-02
    • 2019-08-22
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 2021-09-27
    • 2016-03-01
    • 2015-03-06
    相关资源
    最近更新 更多