我在检查有效性时从指令中获取值时遇到问题。
我的app.js看起来像这样:
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
如果您在输入中写入内容,则输出值{{data.fruitName}}始终为空白。
答案 0 :(得分:0)
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;
});
});
}
};
});
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