0

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"></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>

app.js 如下:

var myApp = angular.module('myApp', []);

myApp.service('sharedata', function() {
    return 'common data';
});

    myApp.controller('firstCtrl', ['$scope', '$http', 'sharedata', function($scope, $http, sharedata) {
        alert('first');
        $scope.numval='first';
        $scope.numval=sharedata;
    }]);

    myApp.controller('secondCtrl', ['$scope', '$http', 'sharedata', function($scope, $http, sharedata) {
        alert('second');
        $scope.numval='second';
        $scope.numval = sharedata;
    }]);

我找不到愚蠢的错误......!我期望无论我在第一个输入框中还是在第二个输入框中更改数据,我都应该看到两个 DIV 标签中反映的更改。

4

1 回答 1

2

尝试以下操作:

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,两者都是<div>

        <input type="text" ng-model="sharedata.numval">
        <p>Inside ___ DIV : {{sharedata.numval}}</p>

你的错误:

  • $scope.numval='first'; $scope.numval=sharedata;没有意义……
  • sharedata服务正在返回一个值;你不能改变一个值;您应该返回包含该值的引用(即对象) 。这样,两个范围都可以写入它。
于 2013-09-20T13:06:07.067 回答