AngularJS. Best practice concerning proper two way data binding from a service

巧了我就是萌 提交于 2019-12-06 13:51:03

There are many questions here, I will answer as best as I can.

No, what you are doing is not a "best practice".

First, The model should be injected directly into the view, and maintaining the value is the responsibility of the Controller, with the help of "$scope". Your "ng-model="Controller.getUserData().UserName" is bad. There is a good example of what to do in the end of the blog article I noticed below.

Second, when you fetch data from a service, most of the time, the answer will be asynchronous, so you'd better take a look at the Promise API. The official doc of AngularJS is not always fantastic and sometimes the answer can be found on google groups or in blog article.

For your problem, here is a good article : http://markdalgleish.com/2013/06/using-promises-in-angularjs-views/

nXqd
  1. Firstly, if you use service in AngularJS, we expect a call to server or whatever that may not return data instantly. So we have two approaches of using ugly callback or beautiful $q.

I prefer using promise since it's cleaner to write. I will rewrite your snippets in a better way :

// Service
angular.module('A').provider('AccountService', [function() {

    this.$get = function ($resource, $q) {

        var Account = {
            getUserData : function () {
                var d = $q.defer();
                d.resolve(Account.userData);
                return d.promise; 
            }    
        };

        return Account;
    }
});

// Controller
angular.module('A').controller('Controller', ['AccountService', function (AccountService) {
    var init = function() {
      getUserData();
    };

    var getUserData = function() {
       AccountService.getUserData().then(function(data) { $scope.username = data; }); 
    };

    init();
    //return $scope.Controller = this; // you don't need to do this 
}])

HTML:

<input id="email" type="email" name="email" ng-model="username"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!