Nick Nick - 5 months ago 22
AngularJS Question

angularjs - scope property not yet available when calling link function

I'm writing a directive.

This is the code i'm using:

angular.module('weather', []).directive('myWeather', [
'$ionicSideMenuDelegate', function($ionicSideMenuDelegate) {
var createWeatherConditionLabel, linkFunction;

createWeatherConditionLabel = function(type) {
var label;
label = '';
debugger;
switch (type) {
case 0:
label = 'Clear';
break;
case 1:
label = 'Clear';
break;
case 2:
label = 'Light Cloud';
break;
case 3:
label = 'Light Cloud';
break;
case 5:
label = 'Windy';
break;
case 6:
label = 'Foggy';
break;
case 7:
label = 'Cloudy';
break;
case 15:
label = 'Rain';
break;
case 18:
label = 'Sleet';
break;
case 21:
label = 'Hail';
break;
case 27:
label = 'Snow';
break;
case 30:
label = 'Showers';
}
return label;
};

linkFunction = function(scope, el, attr) {
console.log("scope:", scope);
scope.showWeatherDetails = false;
scope.evtClickExpandMenuWeather = function() {
if (scope.showWeatherDetails === false) {
return scope.showWeatherDetails = true;
} else {
return scope.showWeatherDetails = false;
}
};
scope.$watch((function() {
return $ionicSideMenuDelegate.isOpenRight();
}), function(isOpen) {
if (!isOpen) {
return scope.showWeatherDetails = false;
}
});
return scope.weatherLabel = createWeatherConditionLabel(scope.weatherType);
};
return {
restrict: 'E',
replace: true,
templateUrl: './directives/tpl.html',
scope: {
weatherData: "=",
weatherType: "="
},
link: linkFunction
};
}
]);


and the directive is called like this:

<my-weather weather-data="zones[0].weatherData" weather-type="zones[0].weatherData.weather_type"></my-weather>


I need to call a function to create
weatherLabel
and use this in the directive template, but I can't because scope.weatherType is undefined.

How can I wait for scope to be defined before calling the link function?

or, is there a better and efficient (performance wise) way to do this? thanks a lot for any help

Answer

1st way: <my-weather ng-if="zones[0].weatherData.weather_type" ... so just your directive is not launched untill variable is resolved. 2nd way: use watch on 'weatherType' in directive and update your label.

P.S. your switch is awesome, but better init map i.e.

var LABELS = {0 : '...', 1 : '...', ...}

and just retrieve label from it.

Comments