2013-10-09 135 views
1

我有指令范围的一些问题...更改根范围

wall.directive('onPaste', function() { 
    return{ 
     restrict: 'A', 
     scope :true, 
     controller: function($scope, $http) { 
      $scope.getUrlInfos = function() { 
       $http({ 
        method: 'POST', 
        data: { 
         firstPost: $scope.firstPost, 
         lastPost: $scope.lastPost 
        }, 
        url: '/wall/json/parseUrl.json' 
       }).success(function(data){ 
        $scope.firstPost = 99; 
        $scope.parseUrl = data; // response data 
        console.log($scope); 
       }); 
      } 

     }, 
     link: function (scope, element, attrs, parentCtrl) { 

      element.bind("paste", function(event) { 
       var element = this; 
       setTimeout(function() { 
        var text = $(element).val(); 
        urls = findUrls(text); 
        scope.$apply(function(){ 
         scope.firstPost = 10; 
         scope.getUrlInfos(); 
        }) 
       }, 100); 
      }); 
     } 
    }; 
}); 

当我console.log($scope);变量具有所有范围......但据我所知它是根范围的副本。屏幕上不显示对该范围的任何更改。我怎样才能将这个范围返回到根范围?

回答

1

假设你有一个定义的根范围,

wall.run(function($rootScope){ 
    $rootScope.firstPost = 1; 
    //..... 
}); 

在AngularJS,$scopes从其父范围prototypically继承,一路到$rootScope。在JavaScript中,当孩子改变它们时,基本类型被覆盖。因此,当您在其中一个控制器中设置$scope.firstPost时,$rootScope上的属性从未触及过,而是将新的可见属性添加到当前范围。

所以你需要通过rootScope指令控制器,然后从那里改变。

wall.directive('onPaste', function() { 
    return{ 
     restrict: 'A', 
     scope :true, 
     controller: function($scope, $rootScope, $http) { 
      $scope.getUrlInfos = function() { 
       $http({ 
        method: 'POST', 
        data: { 
         firstPost: $rootScope.firstPost, 
         lastPost: $rootScope.lastPost 
        }, 
        url: '/wall/json/parseUrl.json' 
       }).success(function(data){ 
        $rootScope.firstPost = 99; 
        $rootScope.parseUrl = data; // response data 
        console.log($rootScope); 
       }); 
      } 

     }, 
     link: function (scope, element, attrs, parentCtrl) { 

      element.bind("paste", function(event) { 
       var element = this; 
       setTimeout(function() { 
        var text = $(element).val(); 
        urls = findUrls(text); 
        scope.$apply(function(){ 
         scope.firstPost = 10; 
         scope.getUrlInfos(); 
        }) 
       }, 100); 
      }); 
     } 
    }; 
});