gpt4 book ai didi

javascript - 如何使用javascript访问 Controller 外部的 Angular 范围

转载 作者:太空宇宙 更新时间:2023-11-04 15:55:04 25 4
gpt4 key购买 nike

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body>

<div ng-app="myApp" ng-controller="myCtrl" id='ang'>
a=<input ng-model="a">
<div>{{a}}</div>
<hr>
b=<input ng-model="b">
<div>{{b}}</div>
<hr>
<div>{{s}}</div>
<button onclick="sum()">calc</button>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.a = 10;
$scope.b = 20;
$scope.s = Number($scope.a) + Number($scope.b);
});


var sum = function () {
//var scope=angular.element($("#ang")).scope();
var scope = document.getElementById("ang");
scope.$apply(function () {
scope.a = 444;
scope.b = 222;
scope.s = 111;
})
}
</script>

</body>

</html>

我正在尝试访问 Angular 外部 Controller 的范围并修改值,但它不起作用。我们可以使用 document.getElement 获取范围,就像使用 angular.element 获取范围一样吗?请看一下并帮助我

最佳答案

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body>

<div ng-app="myApp" ng-controller="myCtrl" id='ang'>
a=<input ng-model="a">
<div>{{a}}</div>
<hr>
b=<input ng-model="b">
<div>{{b}}</div>
<hr>
<div>{{s}}</div>
<button ng-click="sum()">calc</button>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.a = 10;
$scope.b = 20;
$scope.s = Number($scope.a) + Number($scope.b);

$scope.sum = function() {


$scope.a = 444;
$scope.b = 222;
$scope.s = 111;

}
});



</script>

</body>

</html>

为什么你想访问外部 Controller ??试试这个代码

关于javascript - 如何使用javascript访问 Controller 外部的 Angular 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42778174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com