AngularJS 指令scope作用域问题,$apply

项目中发现了一个很奇怪的问题,怎一个郁闷了的....

问题如下

controller中定义了一个变量,$scope.test = "123";

接着定义一个指令,触发事件改变$scope.test = “666666” 此时,$scope.test可以成功修改,输出666666

然后定义了一个$scope.gotest = function(){}函数输出$scope.test,可是,可是,可是...输出结果却是123,我就郁闷了...

代码如下

1、html

<ion-view>
    <ion-content>
        <div class="button-bar">
            <div class="bgstyle" change-element>First</div>
        </div>
        {{test}}
        <a ng-click="gotest()">go</a>
    </ion-content>
</ion-view>
<style>  
    .bgstyle{background-color:#8f8f8f;width:100%;height:30px;margin:2px 0 2px 0;text-align:center} 
</style> 

2、controller

appControllers.controller("ScopeabcCtrl", function ($scope,$rootScope) {
    $scope.test = "123";

    $scope.gotest = function(){
        console.log($scope.test);
    }
})
3、directive

appDirectives.directive("changeElement", function () {
    return {
        scope: false,
        link: function (scope, elements) {
            elements[0].onclick = function () {
                scope.test = "666666";
            };
        }
    };
});


后续...

请教大神之后,发现其实问题是可以解决的,加上scope.$apply(function () {});问题就可以搞定了,代码如下

appDirectives.directive("changeElement", function () {
    return {
        scope:false,
        replace: true,
        link: function (scope, elements) {
            elements[0].onclick = function () {
                scope.$apply(function () {
                scope.test = "666666";
                });
            };
        }
    };
});

或者

appDirectives.directive("changeElement", function () {
    return {
        scope:false,
        replace: true,
        link: function (scope, elements) {
            elements[0].onclick = function () {
              scope.test = "666666";
                scope.$digest();//这个换成$apply即可                
            };
        }
    };
});


$apply回传绑定

$scope.getMessage = function () {
    setTimeout(function () {
        $scope.$apply(function () {
            //wrapped this within $apply
            $scope.message = 'Hello World';
            console.log('message:' + $scope.message);
        });
    }, 2000);
}



猜你喜欢

转载自blog.csdn.net/kingcruel/article/details/65444324