A very strange problem was found in the project, why is it depressed....
Questions are as follows
A variable is defined in the controller, $scope.test = "123";
Then define an instruction to trigger the event to change $scope.test = "666666" At this point, $scope.test can be successfully modified, outputting 666666
Then define a $scope.gotest = function(){} function to output $scope.test, but, but, but... the output result is 123, I am depressed...
code show as below
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"; }; } }; });
Follow up...
After consulting the great god, I found that the problem can be solved, and the problem can be solved by adding scope.$apply(function () {}); The code is as follows
appDirectives.directive("changeElement", function () { return { scope:false, replace: true, link: function (scope, elements) { elements[0].onclick = function () { scope.$apply(function () { scope.test = "666666"; }); }; } }; });
or
appDirectives.directive("changeElement", function () {
return {
scope:false,
replace: true,
link: function (scope, elements) {
elements[0].onclick = function () {
scope.test = "666666";
scope.$digest();//This can be replaced by $apply
};
}
};
});
$apply postback binding
$scope.getMessage = function () { setTimeout(function () { $scope.$apply(function () { //wrapped this within $apply $scope.message = 'Hello World'; console.log('message:' + $scope.message); }); }, 2000); }