2014-04-07 77 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的新手。這真的有幫助。 –