Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 在资源之间共享数据的简单示例不起作用_Angularjs_Service_Controller - Fatal编程技术网

Angularjs 在资源之间共享数据的简单示例不起作用

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

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>
我找不到那个愚蠢的错误。。。。!我希望无论是在第一个输入框中还是在第二个输入框中更改数据,我都会看到两个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>