2014-04-03 10 views
0

Это мой HTMLКак отображать данные, полученные с помощью углового?

  <form name="change_profile_form" ng-controller="profileController" id="change_profile_form" 
      ng-submit="changeProfileForm()"> 

       <input id="username" ng-model="data.User.username" name="username" class="profile_input" disabled value="{{ my_profile.User.username }}" required /> 

Это мои ЯШИ:

var angularApp = angular.module("myApp", ['ngResource', 'myApp.directives']); 


// MyProfile constructor function to encapsulate HTTP and pagination logic 
angularApp.factory('MyProfile', function($http) { 
    var MyProfile = function() { 
    this.user = []; 
    this.profile = []; 
    // this.page = 1; 
    // this.after = ''; 
    // this.perPage = 6; 
    // this.maxLimit = 100; 
    // this.rowHeight = 308; 
    }; 

    MyProfile.prototype.fetch = function() { 
    var url = "https://stackoverflow.com/users/my_profile?callback=JSON_CALLBACK"; 
    $http.defaults.headers.get = { 'Accept' : 'application/json', 'Content-Type' : 'application/json' }; 
    $http.get(url).success(function(data, status, headers, config) { 
     this.user = data.user; 
    }.bind(this)); 
    }; 

    return MyProfile; 
}); 

angularApp.controller('profileController', ['$scope', 'MyProfile', '$users', '$parse', function($scope, MyProfile, $users, $parse) { 
    $scope.my_profile = new MyProfile(); 
    $scope.my_profile.fetch(); 
    $scope.changeProfileForm = function() { 
    var serverMessage = $parse('change_profile_form.email.$error.serverMessage'); 
    $users.changeProfile(
     $scope.data, 
     function(data, status, headers, config) { 
      if (typeof data.error === 'undefined' || typeof data.result === 'undefined') { 
      alert('Server cannot be reached. Please refresh webpage and try again!'); 
      return; 
      } 
      if (data.result != null) { 
      title = "Profile Saved."; 
      message = "Your <strong>PROFILE</strong> has been<br />successfully changed and saved."; 
      options = new Object(); 
      options["box-title"] = new Object(); 
      options["box-title"]["padding-left"] = 5; 
      showOverlayForSuccess(title, message, options); 
      } 
     }, 
     function(data, status, headers, config) { 
      console.log(data); 
      // error callback 
      $scope.errors = data.errors; 
     }) 
    } 
} 

Я проверил вкладку сети в хромовых Дев инструментов. /users/my_profile на заводе не запускается.

Где я понял, что это неправильно?

ответ

0

Я принял логику от http://sravi-kiran.blogspot.com/2013/03/MovingAjaxCallsToACustomServiceInAngularJS.html

Моих изменений являются:

а) понимают, что input уже использует ng-model, следовательно, нет смысла использовать value атрибут

б) перепишут завод и используйте $q

c) внутри контроллера, позвоните по заводскому методу напрямую

Измени)

  <form name="change_profile_form" ng-controller="profileController" id="change_profile_form" 
      ng-submit="changeProfileForm()"> 
       <input id="username" ng-model="data.User.username" name="username" class="profile_input" required style="position: absolute;left:151px;top:<?php echo -138 + $difference; ?>px;"/> 

Изменение б)

// MyProfile constructor function to encapsulate HTTP logic 
angularApp.factory('MyProfile', function($http, $q) { 
    return { 
    getProfile: function() { 
     // creating a deferred object 
     var deferred = $q.defer(); 

     var url = "https://stackoverflow.com/users/my_profile?callback=JSON_CALLBACK"; 
     // prepare headers so that CakePHP can accept the call 
     $http.defaults.headers.get = { 'Accept' : 'application/json', 'Content-Type' : 'application/json' }; 
     // calling the url to fetch profile data 
     $http.get(url).success(function(data, status, headers, config) { 
     // passing data to deferred's resolve function on successful completion 
     deferred.resolve(data); 
     }).error(function() { 
     // sending a friendly error message in case of failure 
     deferred.reject("An error occurred while fetching data"); 
     }); 
     // returning the promise object 
     return deferred.promise; 
    }// end getProfile 
    }// end return 
}); 

Изменение с) и это, как я называю завод внутри контроллера

angularApp.controller('profileController', ['$scope', 'MyProfile', '$users', '$parse', function($scope, MyProfile, $users, $parse) { 
    function getProfile() { 
    MyProfile.getProfile().then(function(data) { 
     $scope.data = data.user; 
     console.log($scope.data); 
    }, 
    function(errorMessage) { 
     $scope.error = errorMessage; 
    }); 
    } 
    getProfile(); 
Смежные вопросы