在AngularJS中,$ watch URL会更改

时间:2018-07-18 14:36:03

标签: javascript angularjs promise

在下面的控制器中,我尝试每次在浏览器中修改URL时获取新值。但是,我每次都得到123。我知道这是因为$watch是异步的,所以我需要使用一个延迟的对象。您如何在这里实现?

//factory
app = angular.module("myApp", [])
app.factory("myAppMain", ["$rootScope", "$location", function($rootScope, $location) {

  URLValue = 123
  return {
    getValue: function() {
      $rootScope.$watch(function() {
          return $location.path()
        }, function(loc) {
          URLValue = $location.path(loc).$$absUrl
        }
      })
    return URLValue
  }
}])

//controller
app1 = angular.module("myApp1", ["myApp"])
app1.controller("myCtrl", ["$scope","myAppMain", function($scope,myAppMain) {
  $scope.newUrl = myAppMain.getValue()
    console.log($scope.newUrl) //  --> keeps printing 123
}])

0 个答案:

没有答案