2015-04-28 36 views
-2

我創建了一個指令,該指令在加載時應顯示國家列表。 當用戶再次訪問頁面時(在SPA內導航後),它應該「記住」所選國家/地區。 我將選定的國家保存在服務中,當頁面再次加載時,我從服務中取回國家,並將其存儲在與選擇框的模型綁定的「scope.country」var中,指示。AngularJs - 將初始對象傳遞給指令

模板:

<select ng-model="country" ng-options="country.Name for country in data.countries" class="form-control"> 
    <option value="">Country</option> 
</select> 

指令:選擇國家並將其設置爲選擇下拉列表中的模型後

.directive('ggCountry', ["$http", function ($http) { 
    return { 
     templateUrl: '../../Common/js/angular/directives/templates/CountryDropDown.html', 
     scope: { 
      country: '=ngModel' 
     }, 

     link: function (scope, element, attrs) { 
      scope.data = {}; 
      scope.data.countries = []; 
      $http.post("../Common/GetAllCountries", {}).then(function (answer) { 
       scope.data.countries = answer.data.d; 
       // select the country: 
       if (scope.country != undefined) { 
        // using underscore library for the selection 
        scope.country = _.where(scope.data.countries, { Id: scope.country.Id }); 
       } 
      }); 
     } 
    }; 
}]) 

,我預計的觀點會有所改變,這國家將被選中,但由於某種原因,它不會這樣做。

回答

0

好吧,這是愚蠢的:)

我用_.where(...)函數,該函數返回一個數組,這不能成爲一個選擇下拉列表中選擇型號。

爲了解決這個問題,我將_.where()更改爲_.findWhere(),它返回可以綁定到的國家對象,並且一切正常。