加载json数据并更新视图

时间:2014-07-22 10:36:55

标签: javascript angularjs

我使用OnsenUI与AngularJS构建搜索应用程序,在第1页上用户输入要搜索的数据,当按下搜索按钮时,page1被压入堆栈并在后台触发get请求以获取请求数据

我使用全局变量来存储从服务和$watch获取的数据,以观察数据中的任何更改,并使用新值更新相应的范围变量。

app.js

(function () {
    'use strict';
    var x;
    var app = angular.module('myApp', ['onsen.directives']);
    app.factory('pageService',['$http', function ($http) {
        var fetchedData;
        return {
            start: function(){
                $http({method: 'GET', url: 'http://127.0.0.1:3000'}).
                success(function(data, status, header, config){
                    console.log('Success !');
                    console.log('Data Name : ' + data[0].name);
                    x = data[0];
                    return data;
                }).
                error(function(data, status, header, config){
                    console.log('fail !');
                    return status;
                })
            },
            getData: function(){
                return fetchedData;
            }
        };
    }]);
    app.controller('page1Ctrl',function($scope,pageService){
        $scope.goToPage2 = function(){
            $scope.x = pageService.start();
            $scope.ons.navigator.pushPage("page2.html");
        }
    });
    app.controller('page2Ctrl',function($scope,pageService){
        $scope.$watch('x',function(newValue, oldValue){
            console.log("x = " + newValue);
            $scope.x = x;
        });
    });

})();

index.html body

<body>
  <ons-screen>
      <ons-page class="center" ng-controller="page1Ctrl">
    <ons-navigator title="Page 1">
        <div class="center">
          <h1>Pharmy</h1>
            <ons-text-input ng-model="medicine" placeholder="Enter Medicine Name" style="display:block; width:100%;" id="test"></ons-text-input>
            <div style="position:relative">
                <ons-text-input ng-model="location" placeholder="Enter Location" style="display:block; width:100%; margin-top:10px;"></ons-text-input>
                <ons-icon icon="search" style="position:absolute;right:10px;top:5px;"></ons-icon>
            </div>
            <ons-button ng-click="goToPage2()"
                        style="width:10%; margin-top:10px;">
                <ons-icon icon="search"></ons-icon>
            </ons-button>
        </div>
    </ons-navigator>
          </ons-page>
  </ons-screen>
</body>

和page2.html

<ons-page class="center" ng-controller="page2Ctrl">
    <ons-navigator-toolbar
        title="Page 2">     
    </ons-navigator-toolbar>
    <h2>Page 2</h2>
    <textarea id="test2" ng-model="x"></textarea>
</ons-page>

我在那里错过了什么?为什么文本区域没有更新?

1 个答案:

答案 0 :(得分:0)

您需要使用Angular Services以避免$ scope。$ watch方法。并简单地$ emit / $广播变量。在第二个控制器中使用$ scope。$ on捕获变量,它将起作用

More Documentation on Services

Documentation on $emit and $broadcast

相关问题