我有一个指令,在其中我使用了 $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/