在 AngularJS 中调用 URL 调用函数

calling a function on url call in angularjs

本文关键字:调用 URL 函数 AngularJS      更新时间:2023-09-26

我对angularjs很陌生,需要帮助在url调用时调用函数。我使用 url 直接访问查询参数

http://localhost/index.html#/?defined=true&var1=value1&var2=value2&

$location.search()['defined'];

现在,在我的控制器中,我有一个函数"caller",它在 html 页面上的 ng-change、ng-model 等事件上被调用,工作正常

angular.module('ngAp').controller
('ngCntrl',function($scope,$http,$location{
    $scope.caller = function() {
       // code logic 
    }
}

我正在尝试做的是在直接访问上述 url 时调用函数"caller"

$location.search()['defined'];
if (defined == "true" )
{ //call the caller function.
}

我不知道当我直接调用 url 时如何调用该函数。任何帮助将不胜感激。

如果你看看$location的文档 - https://docs.angularjs.org/api/ng/service/$location

它有一些您可以使用的事件,例如 $locationChangeStart .但最好在 angular.module('ngAp').run(...) 中绑定到此事件。

angular.module('ngAp').run(moduleRun);
function moduleRun ($location, $rootScope) {
  $location.on('$locationChangeStart', function (event, newUrl, oldUrl, newState, oldState) {
    var defined = $location.search()['defined'];
    $rootScope.defined = defined //you can assign it to $rootScope;
    if (defined === "true" ) {
      //call the caller function.
    }
  })
}