Angularjs 在资源之间共享数据的简单示例不起作用
index.html如下所示:Angularjs 在资源之间共享数据的简单示例不起作用,angularjs,service,controller,Angularjs,Service,Controller,index.html如下所示: <!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> <meta charset="utf-8"> <title>HTTP Request</title> <script src="angularjs"></script> <script src="appjs"></
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>HTTP Request</title>
<script src="angularjs"></script>
<script src="appjs"></script>
</head>
<body>
<p>Data sharing example :</p>
<div ng-controller="firstCtrl">
<input type="text" ng-model="numval">
<p>Inside first DIV : {{numval}}</p>
</div>
<div ng-controller="secondCtrl">
<input type="text" ng-model="numval">
<p>Inside second DIV : {{numval}}</p>
</div>
</body>
</html>
我找不到那个愚蠢的错误。。。。!我希望无论是在第一个输入框中还是在第二个输入框中更改数据,我都会看到两个DIV标记中反映的更改。尝试以下操作:
var myApp = angular.module('myApp', []);
myApp.service('sharedata', function() {
return {numval: "Something"};
});
myApp.controller('firstCtrl', ['$scope', '$http', 'sharedata',
function($scope, $http, sharedata) {
alert('first');
$scope.sharedata = sharedata;
}]
);
myApp.controller('secondCtrl', ['$scope', '$http', 'sharedata',
function($scope, $http, sharedata) {
alert('second');
$scope.sharedata = sharedata;
}]
);
和HTML,都是
s:
<input type="text" ng-model="sharedata.numval">
<p>Inside ___ DIV : {{sharedata.numval}}</p>
在_DIV内:{{sharedata.numval}
你的错误:
$scope.numval='first'$scope.numval=共享数据代码>没有意义
服务正在返回一个值;不能更改值;您应该返回包含该值的引用(即对象)。这样,两个作用域都可以写入它sharedata
<input type="text" ng-model="sharedata.numval">
<p>Inside ___ DIV : {{sharedata.numval}}</p>