我正在尝试使用 Controller 访问图像 src 以保存它,但不知道该怎么做。
我的模板:
<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>
我的 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);
}
};
}])
最佳答案
一种选择是使用 directive并对其应用一个名为 save 的方法,该方法将处理在图像标签上找到的 src 属性。
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.
另一种选择是将作用域与 Controller 隔离,但仍将图像应用于 Controller 而不是函数。
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>
注意添加的 ng-controller="cntl"。
This is the JSfiddle for that one.
关于Angularjs。从 AngularJS Controller 访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17093949/