AngularJS 指令scope作用域問題,$apply
阿新 • • 發佈:2019-01-31
專案中發現了一個很奇怪的問題,怎一個鬱悶了的....
問題如下
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);
}