<!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>
我试图访问角度外部控制器的范围并修改值,但它不工作。我们使用document.getElement获取范围,因为我们可以使用angular.element? 请看看它并帮助我
答案 0 :(得分:1)
<!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>
为什么要访问外部控制器。试试这段代码
答案 1 :(得分:0)
试用此代码
var demo = angular.module('demo', []);
demo.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();
scope.$apply(function(){
scope.a = 444;
scope.b = 222;
scope.s = 111;
})
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script>
<div ng-app='demo'>
<div 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>
</div>
&#13;