加载json数据并更新视图

Loading json data and updating view

本文关键字:更新 新视图 数据 json 加载      更新时间:2023-09-26

我使用OnsenUI与AngularJS来构建一个搜索应用程序,在page1上用户输入要搜索的数据,当按下搜索按钮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>
  <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>

我错过了什么?为什么文本区域不更新?

你需要使用Angular Services来避免使用$scope。美元的观察方法。然后简单地$emit/$broadcast变量。在第二个控制器中,使用$scope捕获变量。$on,它将工作

关于服务的更多文档

关于$emit和$broadcast的文档