2015-04-28 27 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(),它返回可以绑定到的国家对象,并且一切正常。