getting and setting value in factory in angualrjs

后端 未结 6 1256
执笔经年
执笔经年 2020-12-12 04:40

This is my factory:

.factory(\'userService\',()){
  var user = {};
  return {

  getFirstname : function () {
    return user.firstname;
  },

  setFirstname         


        
6条回答
  •  一向
    一向 (楼主)
    2020-12-12 05:18

    You have two options to overcome this problem.

    Solution 1st:

    Adding a watch in your controller.

    .controller('MainCtrl',['userService', function(userService) {
    
        $scope.userName = userService.getFirstName();
    
        $scope.$watch(function() {
            return userService.getFirstName();
        }, function(newValue) {
           $scope.username = newValue;
        });
    }]);
    

    Solution 2nd:

    .controller('MainCtrl',['userService', function(userService) {
    
        $scope.getUsername = function() {
            userService.getFirstName();
        };
    
    }]);
    

    Now your view should directly call this function.

    {{getUsername()}}

    Now, according to Angular's doc, whenever the return value from a function call changes, Angular will update the values in the view.

提交回复
热议问题