I am new to angularjs and want to add new feature in existing code. But code is not working as expected. I know i am not doing it the right way. Please correct me where is the mistake. I don't know why controller is not used but directive is used in this approach?
Here is my custom service and custom directive directive code.
Service code:
angular.module("quickquiz-builder").service("SettingsService", function ($http, $q) {
return {
/* Return deffered promise response */
get: function() {
var deferred = $q.defer();
$http.get('get.php')
.then(function(response){
var config = response.data.config;
config = JSON.parse(config);
this.generalSettings = config.settings;
deferred.resolve(this);
})
.catch(function(response){
deferred.reject(response);
});
return deferred.promise;
}
}
})
Custom Directive:
angular.module("quickquiz-builder").directive("quizbuilderSettings", ["SettingsService", "QuestionsService", "$filter", function (SettingsService, QuestionsService, c) {
return {
restrict: "E",
scope: {},
templateUrl: "templates/settings.html",
controllerAs: "ctrl",
controller: ["$scope", function (scope) {
SettingsService.get().then(function (data){
/* get response from service inside callback */
this.settingsService = data;
scope.settingsService = this.settingsService;
this.questionsService = QuestionsService;
console.log(1);
console.log(scope.settingsService.generalSettings);
console.log(1+' end');
}).catch(function(e){
console.dir(e);
});
}]
}
}])
The service response is retrieved successfully inside callback in directive. But this response is not binding with view.
A piece of template code is:
<div layout="row" class="option">
<md-switch class="md-primary var-label" aria-label="graded" ng-model="ctrl.settingsService.generalSettings.graded" ng-change="ctrl.onChangeGraded()">
<strong>Graded</strong>
</md-switch>
<p flex=""><span ng-if="ctrl.settingsService.generalSettings.graded">The quiz has at least one graded question (a question that has a right/wrong answer).</span><span ng-if="!ctrl.settingsService.generalSettings.graded">It's not a graded quiz.</span>
</p>
</div>