Angularjs。从 AngularJS Controller 访问属性

标签 angularjs

我正在尝试使用 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/

相关文章:

javascript - angularjs 模型值在表单中未定义

javascript - 在 angularjs 工厂中使用 setInterval

javascript - 使用 ng-model 数组

动画运行时 CSS 动画出现在顶部

java - 为什么我的两个不同的 angularjs 服务解析为同一个 Restful Java EE Web 服务?

javascript - 使用 Angular 和javascript对表进行条件格式化

angularjs - 在 $save 回调中替换 $resource master/copy 无法触发 $watch

javascript - 资源解释为脚本,但在注入(inject) angular-route.map 时以 MIME 类型 text/html 传输

angularjs - 向 ng-grid 列添加属性

javascript - Angular 谷歌地图不更新标记