更改根范围

时间:2013-10-09 08:34:20

标签: angularjs laravel angularjs-directive angularjs-scope

我在指令范围方面存在一些问题......

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 个答案:

答案 0 :(得分:1)

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

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

在AngularJS中,$scopes原型继承自其父范围,一直到$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);
            });
        }
    };
});