我在 Angular 1.x 控制器中使用 d3.js 库。我的 d3.js 库在 div 上创建了一个单击事件,当单击 div 时,它会更新角度控制器范围内的某些内容。
问题是,当我更改范围($scope.test = "a test"
)时,修改没有报告到模板中。
但是,如果在该 d3.js 点击事件中,我执行 $scope.$apply (如相关主题所建议:Angular + D3 - Get scope values to show in template from click event),则更新 dom 并且一切工作正常。
由于不鼓励使用范围,是否有另一种解决方案可以使更改出现在我的模板中?
这是我的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.1/d3.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
</head>
<body>
<div ng-app="app" >
<div id="main" ng-controller="main">
test is {{test}}
<div id="graph">
hello
</div>
</div>
</div>
</body>
<script type="text/javascript">
var app = angular.module('app',[]);
app.controller('main', function($scope){
$scope.force_refresh = function(){}
d3.selectAll("#graph").on("click", function() {
$scope.test = "a test";
//////////I would like to avoid this/////////////
$scope.$apply(); ////////////////////
//////////I would like to avoid this/////////////
});
});
</script>
</html>