I'm begginer in angularjs. I have an angular directive and using it ASP.NET MVC project:
'use strict';
app.directive('province', function (Province, $rootScope) {
return {
restrict: 'E',
replace: true,
template: '<select data-ng-model="province" data-ng-options="province.provinceId as province.provinceName for province in provinces" ' +
'data-ng-change="provinceChanged()"></select>',
link: function (scope, element, attr, controller) {
Province.get().then(function (provinces) {
scope.provinces = provinces;
});
console.log(scope.provinces);
scope.province = false;
scope.provinceChanged = function () {
if (!scope.province) {
return;
}
$rootScope.$broadcast("provinceChanged", { province: scope.province });
};
}
};
})
This is the way I use it:
<province id="province" class="form-control" data-selected-province="@Model.Province"/>
The select element shows provinces corrctly. Now I want to set a default value for select element. So I use attribute data-selected-province and set it to the value that I get from server(@Model.Province). I think I should loop through scope.provinces and find the index of the province whose provinceId is equal to data-selected-province attribute and set scope.province which is ng-model to that index. But scope.provinces is undefined when I print it to the console using console.log. I have two questions:
- why
scope.provincesis null? - Is this the correct way of setting default value?
UPDATE
I was a bit confused. The only thing I need to do is set scope.province to attr.selectedProvince. But I still have a problem. When I set scope.province to a constant number like scope.province = 8 it works fine but when I set data-selected-province = 8 it does not work. I can see in firebug that this attribute is equal to 8 when rendering the directive.
Any help is appreciated in advance.