javascript - 在指令中使用 $location.url() 在 angularjs 中不起作用

标签 javascript angularjs angularjs-scope

我有一个指令,在其中我使用了 $location.url()但它似乎不起作用,我想我需要在我的应用程序上注入(inject)一些东西,但我不知道在哪里注入(inject)它。顺便说一句,我是 angularJS. 的新手这是我的代码:

app.controller('CVSRRC-CTRL', function($scope,$http,$location){

        // some codes here

});
app.directive('cvsrrc', [function(){
return {
    restrict: 'A',
    link: function(scope, element, attrs){
        element.bind('dblclick', function(){
            $location.url("admin");
        });
      }
    }
}]);

它不起作用,但我尝试替换 $location.url("admin");alert(1)它工作正常。当我检查控制台时,它显示 $location is undefined 。我该怎么办?

最佳答案

当事件来自 AngularJS 框架外部时,框架需要使用 $apply 启动一个摘要循环。

app.controller('CVSRRC-CTRL', function($scope,$http,$location){
    // some codes here
});
app.directive('cvsrrc', ['$location', function($location){
return {
    restrict: 'A',
    link: function(scope, element, attrs){
        element.bind('dblclick', function(){
            $location.url("admin");
            scope.$apply();
        });
      }
    }
}]);

Using $location outside of the scope life-cycle

$location knows about AngularJS's scope life-cycle. When a URL changes in the browser it updates the $location and calls $apply so that all $watchers / $observers are notified. When you change the $location inside the $digest phase everything is ok; $location will propagate this change into browser and will notify all the $watchers / $observers. When you want to change the $location from outside AngularJS (for example, through a DOM Event or during testing) - you must call $apply to propagate the changes.

-- AngularJS Developer Guide - Using $location Outside Scope Life-Cycle

关于javascript - 在指令中使用 $location.url() 在 angularjs 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41928298/

相关文章:

javascript - 将 javascript 添加到 200 多个 html 文件,最简单的方法?

javascript - xmlhttprequest 无法仅使用 post 方法加载 'access-control-allow-origin' (Angularjs)

angularjs - npx cap 同步 vs npx cap 复制标签 : 1) ionic 2) capacitor

javascript - 观察数组的子值

javascript - jQuery 显示数组项给我 [object, Object]

javascript - 如何有效地随机选择数组项而不重复?

javascript - AngularJS - Controller 和工厂 - 我在包含/注入(inject)函数时哪里出错了?

javascript - 错误 : No controller: ngModel

javascript - 删除字符串中元音之前的所有辅音,然后添加一个字符

javascript - 如何在 Angular Js 的所有 Controller 中管理用户详细信息