This is only my 2nd AngularJS project. I'm trying to add new functionality to an existing jQuery app rather than starting over.
The jQuery portion populates a div with several image thumbnails. The purpose of the new AngularJS features is to allow the user to edit the information for the photos - caption, photographer credit, and such. Clicking a thumbnail should trigger the Angular app to retrieve its info from the database for edit. My problem is, the image URL is never picked up by Angular.
The ng-app tag is placed on the page's body element, so everything should be visible to Angular. I have tried $scope.$watch and $scope.$apply with no success. The URL of the clicked image does appear in expected locations, but the Angular model element "imgurl" never seems to get updated despite using ng-model="imgurl" on the text input field.
I have looked at similar questions such as these:
- I can't detect programmatically value change in angularjs
- AngularJS : ng-model binding not updating when changed with jQuery
My existing jQuery, trying to push data into Angular
function populateImageForm(imageURL) {
jQuery("#imageurltest").html("clicked image is " + imageURL); //show the URL of the clicked image
//updates the image, but Angular doesn't see change: jQuery("#working-image").attr("src", imageURL);
jQuery("#working-image").attr("ng-src", imageURL);
jQuery("#wiurl").val(imageURL);
}
HTML elements using Angular:
<img id="working-image" class="center-block img-responsive" ng-src={{imgurl}} imageonload />
<input id="wiurl" type="text" size="65" ng-model="imgurl" />
Angular controller code:
app.controller("imageInfoControl", function($scope, $http) {
$scope.imgurl = "http://example.org/placeholder.jpg";
$http.get("ng-get-image.php", {params:{"url": $scope.imgurl}} ).success(function(response){
console.log (response);
$scope.message = response.title;
});
$scope.$watch('imgurl',
function(newVal, oldVal) {
console.log('imgurl programmatically changed');
});
$scope.$watch(function() {
return $scope.message
}, function(newVal, oldVal) {
if(newVal !== null) {
console.log('message programmatically changed to ' + $scope.message);
}
});
});
app.directive('imageonload', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('load', function() {
console.log (element);
console.log (attrs);
//doesn't seem to do anything: scope.$apply(attrs.imageonload); https://stackoverflow.com/questions/17884399/image-loaded-event-in-for-ng-src-in-angularjs
scope.$digest;
scope.message = attrs.src;
console.log(scope.message);
//alert('image is loaded');
});
element.bind('error', function(){
alert('image could not be loaded');
});
}
};
});