【问题标题】:Angularjs Sharing Data between Controllers using factoryAngularjs使用工厂在控制器之间共享数据
【发布时间】:2014-06-23 05:16:41
【问题描述】:

我正在关注 YouTube 的 tutorial 在控制器之间共享数据。 出于某种原因,这两个输入不返回共享数据(不可绑定)。谁能让我知道我的代码有什么问题?

 <!DOCTYPE html>
    <html class="no-js">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">
        <link rel="stylesheet" href="/css/app.css?2">
        <script src="/bower-foundation/js/vendor/modernizr.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js?2"></script>
        <!-- angularjs -->
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
        <script>
            var myApp = angular.module('myApp', []);

            myApp.factory('Data', function(){
                return {msg:"I am data from a service"}
            })

            function firstctrl($scope, Data) { 
                $scope.data = Data;
            }
            function secondctrl($scope, Data) {
                $scope.data = Data;
            }
        </script>
    </head>
    <body ng-app="myApp">


        <div ng-controller="firstctrl">
            <input type="text" ng-model="data.msg">
            <h1>{{data.msg}}</h1>
        </div>


        <div ng-controller="secondctrl">
            <input type="text" ng-model="data.msg">
            <h1>{{data.msg}}</h1>
        </div>


    <!-- javascript -->
        <script src="/bower-foundation/js/foundation.min.js?3"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/fastclick/0.6.11/fastclick.min.js?2"></script>
        <script src="/js/min/app.min.js?3"></script>
    </body>
    </html>

【问题讨论】:

标签: angularjs


【解决方案1】:

它工作正常,看看这个

Working Demo

HTML

<div ng-app='myApp'>
    <div ng-controller="firstctrl">
        <input type="text" ng-model="data.msg" />
         <h1>{{data.msg}}</h1>

    </div>
    <div ng-controller="secondctrl">
        <input type="text" ng-model="data.msg" />
         <h1>{{data.msg}}</h1>

    </div>
</div>

脚本

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

myApp.factory('Data', function () {
    return {
        msg: "I am data from a service"
    };
})

function firstctrl($scope, Data) {
    $scope.data = Data;
}

function secondctrl($scope, Data) {
    $scope.data = Data;
}

也看看这些东西

AngularJS - Sharing variables between controllers

【讨论】:

  • 很奇怪,当我更新输入时,两个数据都没有返回。 h1 仅在编译后显示 {{data.msg}}。
  • 不要看到数据值打印在像 h1 这样的文本字段中......并且每当您更改值时,它都会反映在所有区域中
  • 表示当您更改一个文本字段值时,您不希望另一个文本字段值得到反映.....您能否详细说明您的要求。 ...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-15
  • 2014-03-22
  • 1970-01-01
  • 2013-05-28
相关资源
最近更新 更多