Angularjs. Attribute Access from AngularJS Controller

I am trying to get an src image with a controller in order to save it, but cannot figure out how to do it.

My template:

<img data-ng-model="book.image" style="width: 300px; height: 200px;" ng-src="data:image/png;base64,iVBORw0K...SuQmCC"> <a data-ng-click="save(book)" class="btn">Submit</a> 

My controller:

  controller('BookEditController', [ '$scope', '$meteor', function ($scope, $meteor) { $scope.save = function (book) { if (typeof book == 'object') { var books = $meteor("books"); var id = books.insert(book); } }; }]) 
+4
source share
2 answers

One option uses directive and uses a method called save, which will handle the src attribute found in the image tag.
Js

 var app = angular.module('myApp', []); app.directive('saveImage', function () { return { transclude: true, link: function (s, e, a, c) { s.save=function(){ alert(a.src); }; } }; }); 

HTML

 <div > <img save-image style="width: 300px; height: 200px;" src="http://placehold.it/350x150"> <a ng-click="save()" class="btn">Submit</a> </div> 

This is the code implemented in jsfiddle.

Another option is to isolate the scope to the controller, but still apply the image to it instead of the function.

Js

 var app = angular.module('myApp', []); app.directive('saveImage', function () { return { transclude: true, link: function (s, e, a, c) { s.image = a.src; } }; }); function cntl($scope) { $scope.save = function (img) { alert($scope.image || 'no image'); } } 

HTML

 <div ng-controller='cntl'> <img save-image style="width: 300px; height: 200px;" src="http://placehold.it/350x150"> <a ng-click="save()" class="btn">Submit</a> </div> 

Note the added ng-controller = "cntl".

This is JSfiddle for this.

+5
source

Probably the best way to do this ... pass $event to your controller function

 <a data-ng-click="save(book, $event)" class="btn">Submit</a> 

and then use workarounds to find the img tag and its src attr:

 $scope.save = function (book, ev) { console.log(angular.element(ev.srcElement).parent().find('img')[0].src); ... 

Update : the best way is to create a directive (e.g. @mitch), but I would use the = binding in the selection area to update the src property in the parent area, ( = makes it clear that the directive can change the scope. I think this is better, than with a directive add a method or property to the controller area "backstage".)

 <div ng-controller="MyCtrl"> <img save-image book="book1" src="http://placehold.it/350x150" > <a href="" ng-click="save(book1)">Submit</a> </div> 

 function MyCtrl($scope) { $scope.book1 = {title: "book1" }; // src will be added by directive $scope.save = function(book) { alert(book.title + ' ' + book.src); } } app.directive('saveImage', function () { return { scope: { book: '=' }, link: function (s, e, a, c) { s.book.src = a.src; } }; }); 

Plunker

+1
source

Source: https://habr.com/ru/post/1486081/


All Articles