将值从服务传递到AngularJS中的控制器

时间:2018-07-17 21:40:35

标签: javascript angularjs global-variables

我很难将更新后的值从下面的全局变量URLValue传递给控制器​​。它保持打印12345。有什么想法吗? 似乎更新后的URLValue不会传递给函数watchingURL返回的结果,我不确定为什么原因,因为URLValue是全局变量。

 var URLValue = '12345';
 factoryModule = angular.module("factoryDetails" ,[])
.factory( "factoryMain" , ["$sce" ,"$location", "$rootScope", "$q",

    function($sce,$location, $rootScope,$q){
      this.watchingURL = function() { 
        $rootScope.$watch(function () {
          return  $location.path();
        },  
        function (loc) {
          console.log("$location.path() ",$location.path(loc).$$absUrl);
          temp = $location.path(loc).$$absUrl
          URLValue = 789;
        })
        return URLValue;
      };
}]);



app.controller("appController", ["$scope", "factoryMain" 
  function($scope,factoryMain) {
    $scope.name = factoryMain.watchingURL();
    console.log("function passed is" , factoryMain.watchingURL());
    $scope.$watch(factoryMain.watchingURL(), function(newval,oldval){
        $scope.name=newval
        console.log("oldval is ",oldval)
        console.log("newval is ",$scope.name) 
    });
}]);

当将此服务传递给我的控制器时,我得到URLValue = 12345 有什么主意吗?

0 个答案:

没有答案