2014-04-07 79 views
4

嗨,我有一个问题。 我有一个对象,我厂更新控制器变量更新Angular工厂变量

User: { 
    EmailAddress: "" 
} 

以下每当我做HTTP调用我想更新User.EmailAddress蒙山返回值。在工厂内进行工作的最佳方式是什么?所以在控制器级别,我可以将我的$ scope.Email绑定到工厂变量。这就是我现在

GetLogOnModel: function() { 
    if ($location.path().indexOf("login") == 1) { 
     var promise = $http.get(config.headers.url + "LogOn").then(function (response) { 
      // The return value gets picked up by the then in the controller. 
      User.EmailAddress=response.data.Email; 
      return response.data 
     }); 
     return promise; 
     // Return the promise to the controller 
    } 
} 

并在控制器

AccountFactory.GetLogOnModel().then(function (data) { 
    $scope.logOnModel = data; 
}, function (err) { 
    console.log(err.reason); 
    alert(err.reason); 
}); 
+0

工厂变量是否在控制器外面被更新? –

+0

@ShidhinCr是的,我正在更新它在工厂内... –

+0

我是否必须申请$ scope.watch如果是的话,几乎在每个控制器我必须这样做?我认为这不是一个好主意..因为它是反对DRY .. –

回答

13

基本类型(如字符串)不被约束参考做。因此,您无法直接将范围属性绑定到EmailAddress,并希望它自动更新。在另一方面
对象是通过引用约束,所以你可以做这样的事情:

app.factory('AccountFactory', function (...) { 
    ... 
    var User = { 
    ... 
    EmailAddress: null 
    }; 

    function getLogOnModel() { 
    $http.get(...).then(function (response) { 
     User.EmailAddress = response.data.Email; 
    }); 
    } 

    // Init model (or leave it for the controller to init it) 
    getLogOnModel(); 

    return { 
    ... 
    User: User, 
    getLogOnModel: getLogOnModel 
    }; 
}); 

app.controller('someCtrl', function (..., AccountFactory) { 
    $scope.user = AccountFactory.User; 
    // Now you can reference `$scope.user.EmailAddress` 
    // and it will be kept in sync with `AccountFactory.User.EmailAddress` 
}); 
+0

谢谢你解决了我的问题....另一个问题是我从后端返回一个空模型并希望实现相同的目标 –

+0

对不起,我没有得到这个其他问题空模型。 – gkalpak

+0

这是我的另一个问题与您的示例代码(位修改虽然)http://stackoverflow.com/questions/22911354/get-empty-model-from-backend-in-angularjs-factory-and-update-controller-variable –

7

它应该是相当直截了当。您可以将服务实例或电子邮件属性绑定到$scope

这里我只是在5秒后更新电子邮件。

myApp.factory('myService', function($http, $timeout) { 
    return { 
     email: '[email protected]', 
     updateEmail: function() { 
      var self = this; 
      $timeout(function() {     
       $http.get('/echo/json/').success(function() { 
        self.email = '[email protected]'; 
       }); 
      }, 5000); 
     } 
    }; 
}); 

第1种方法: 绑定的范围为整个服务:

​​

第2种方法 只需创建一个自定义$watch电子邮件通知:

function MyCtrl($scope, myService) { 
    $scope.email = myService.email; 
    myService.updateEmail(); 

    $scope.$watch(function() { return myService.email; }, function(newVal, oldVal) { 
     $scope.email = newVal; 
    }); 
} 

<div ng-controller="MyCtrl"> 
    $scope: {{email}} 
</div> 

我会推荐第一种方法b因为它只需要一个$watch来更新DOM,即对于{{myService.email}},而第二种方法需要两个$watches,即一个用于更新$ scoped模型($scope.$watch),另一个用于更新DOM作为{{email}}

演示:http://jsfiddle.net/HB7LU/3015/

+1

第一种方法对我很好。我是AngularJs的新手。这真的有帮助。 –