Angular中的ajax调用和$ .watch

时间:2015-10-27 18:19:49

标签: json ajax angularjs

单击按钮时,我需要生成一个选择菜单。我点击按钮时,我正在进行ajax调用以从外部文件中获取json数据。反过来应该使用json中的数据更新select。使用下面的代码,只有在单击按钮两次后才会更新。我正在观看jsonData,但它没有按预期工作。

HTML:

 <div ng-controller="MainViewCtrl">
   <button ng-click="getDeployedResources()"> Load Resources </button>
   <select ng-model="selectedOption.name" ng-options="item.name as item.name for item in jsonData"></select>
 </div>
来自dropdown.json的

json:

{
    "DeployedResources": {
        "-env": "dev13",
        "ResourceList": {
            "-exportTime": 1444999007878,
            "Resource": [{
                    "name": "default",
                    "type": "project"
              },
                {
                    "name": "System",
                    "type": "project"
               },
                {
                    "name": "StratusCommonServices",
                    "type": "project"
              }]
           }
       }
}

JS:

var app = angular.module('JSONedit', ['ui.sortable'])

.controller('MainViewCtrl', ['$scope', '$http', '$filter','$compile',   function ($scope, $http, $filter, $compile) {
$scope.jsonData = {};

$scope.getDeployedResources = function () {
    $.ajax({
        url: 'json/dropdown.json',
        dataType: 'json'
    }).done(function (data) {
        $scope.jsonData = data.DeployedResources.ResourceList.Resource;
        $scope.selectedOption = angular.copy($scope.jsonData[0]);
    });
}


$scope.$watch('jsonData', function (json) {
    $scope.jsonString = $filter('json')(json);
}, true);
$scope.$watch('jsonString', function (json) {
    try {
        $scope.jsonData = JSON.parse(json);
        $scope.wellFormed = true;
    } catch (e) {
        $scope.wellFormed = false;
    }
}, true);

}])

1 个答案:

答案 0 :(得分:1)

这是一个简单的AngularJS组件的正确生命周期! 不要使用jQuery做一些角度更好的事情!

angular
  .module('test', [])
  .service('DataService', function($q, $http) {
    var self = this;

    var mock = {
      id: 1,
      "DeployedResources": {
        "-env": "dev13",
        "ResourceList": {
          "-exportTime": 1444999007878,
          "Resource": [{
            "name": "default",
            "type": "project"
          }, {
            "name": "System",
            "type": "project"
          }, {
            "name": "StratusCommonServices",
            "type": "project"
          }]
        }
      }
    };

    self.load = function() {
      console.log('loading data', mock.id);
      for (var i = 0, len = mock.DeployedResources.ResourceList.Resource.length; i < len; i++) {
        mock.DeployedResources.ResourceList.Resource[i].name += mock.id;
      }

      mock.id += 1;
      return $q.when(mock);

      return $http
        .get('/api/data/')
        .then(function(result) {
          return result.data;
        });
    }
  })
  .controller('TestCtrl', function($scope, DataService) {
    var vm = $scope;
    
    vm.select = {
      current: null,
      items: []
    };

    vm.loadData = function(event) {
      console.count('load data');

      return DataService
        .load()
        .then(function(data) {
          vm.current = data.id;
          return data.DeployedResources.ResourceList.Resource;
        })
        .then(function(items) {
          vm.select.items = items;
          vm.select.current = vm.select.items[0];
        })
    };

    vm.loadData();
  });
.select-wrapper {
  padding: 1em 2em;
  background: yellow;
}
.select-wrapper select {
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>

<article ng-app="test">
  <div ng-controller="TestCtrl">

    <button type="button" ng-click="loadData($event);">LoadNew</button>
    <div class="select-wrapper">
      <select ng-model="select.current" ng-options="item as item.name for item in select.items"></select>
    </div>
    <div ng-bind="select.items | json"></div>
  </div>
</article>