Using factory in directive
-
21-12-2019 - |
Question
I have problem to get the value from directive back while checking the validity.
My app.js look like this:
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.doSomething = function () {
alert('Submitted!');
}
});
app.directive('imgExist', function (ImgChck){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
ctrl.$parsers.unshift(function(value) {
ImgChck.isImage(value).then(function(result) {
ctrl.$setValidity('imgexist', true);
return 'http://cdn1.imgs.bigtitinvasion.com/t1/episodes/shylastylez/shyla-big-tit-slut-big3.jpg'; //value
},
function(result) {
ctrl.$setValidity('imgexist', false);
return undefined;
});
});
}
};
});
app.factory('ImgChck', function($q) {
return {
isImage: function(src) {
var deferred = $q.defer();
var image = new Image();
image.onerror = function() {
deferred.resolve(false);
};
image.onload = function() {
deferred.resolve(true);
};
image.src = src;
return deferred.promise;
}
};
});
Plunkr: http://plnkr.co/edit/spgFCC3fIjNprwsZJET9?p=preview
If you write something in input the output value {{data.fruitName}} is always blank.
Solution
Directive
app.directive('imgExist', function(ImgChck) {
return {
restrict: 'A',
require: 'ngModel',
scope: {
model: '=ngModel'
},
link: function(scope, elem, attr, ctrl) {
if (!ctrl) return;
scope.$watch("model", function(value) {
ImgChck.isImage(value).then(function(result) {
ctrl.$setValidity('imgexist', true);
return value;
}).
catch(function() {
ctrl.$setValidity('imgexist', false);
return value;
});
});
}
};
});
Factory
app.factory('ImgChck', function($q) {
var ImgChck = {};
ImgChck.isImage = function(src) {
var deferred = $q.defer();
var image = new Image();
image.onerror = function() {
deferred.reject(false);
};
image.onload = function() {
deferred.resolve(image);
};
image.src = src;
return deferred.promise;
}
return ImgChck;
});
Plunker: http://plnkr.co/edit/YqErhEQDDdZPvQeDOhbG?p=preview
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow