(十五)在controller之外修改$scope中的数据,双向绑定特性失效,不能自动刷新

本文探讨了在AngularJS中,当在ng-controller外部修改$scope数据时,双向绑定特性失效的问题。通过示例代码展示了即使功能相同,controller外部的方法无法使$scope自动刷新。为了解决这个问题,提出了手动调用$scope.$digest()来触发脏值检测,以实现数据刷新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在angularjs中通过angular.element(dom).scope()可以拿到某个dom元素关联的作用域,从而可以访问$scope中的属性和方法。但是在ng-controller函数之外修改$scope中的数据,angular的$scope是不会自动刷新的,即双向绑定特性失效。

<html>
  <head>
    <script src="angular-1.3.15.js"></script>
	<script>
        var app = angular.module('app', []);  
        app.controller("myController",function($scope){
			$scope.buttonAdisable = true;
			$scope.buttonBdisable = true;
			
			//让a按钮可用
			$scope.enableA=function(){
				$scope.buttonAdisable=false;
			};
		});  
   
		// 启动模块
        angular.element(document).ready(function() {  
              angular.bootstrap(document.getElementById("root_div"),["app"]); 
        }); 
	 
		// 让b按钮可用
		function enableB()
		{
			var scope = angular.element(document.getElementById('b')).scope();
			scope.buttonBdisable=false;
		}
	</script>
  </head>
  <body>
		<div id="root_div