这可能是一个基本问题。通常我从我的指令中设置值。我从来没有从指令中获得价值。
这是一个名为snapshot的简单指令。基本上这使用你的相机拍照,标记X然后生成一个json。我会削减代码,不要让人们混淆......:
<snapshot width="640" height="480"></snapshot>
angular
.module('snapshot', [])
.directive('snapshot', function () {
return {
restrict: 'E',
scope: {
width: "=",
height: "="
},
template: 'html template here',
controller: function ($scope, $element) {
$scope.data = {
x : null,
y: null,
image: null
}
$scope.mark = function(event)
{
$scope.data.x = event.clientX;
$scope.data.y = event.clientY;
}
$scope.takeSnapshot = function()
{
var context = canvas.getContext("2d");
context.drawImage(video, 0, 0, $scope.width, $scope.height);
$scope.gotIt = true;
$scope.cameraOn = false;
$scope.setMarker = true;
$scope.data.image = canvas.toDataURL("image/jpeg");
}
}
}
});
所以,我需要在指令外面阅读我的$ scope.data,我不知道怎么做。
让我尝试为此创建一个假设的HTML ...
<snapshot width="640" height="480"></snapshot>
<p>My data of my directive is : {{snapshop.data}}</p>
得到了我的想法?那么,有人可以帮我解决这个问题吗?
tyvm !!!
答案 0 :(得分:3)
与提到的Fals一样,您可以将数据对象作为属性传递。然后,您可以直接修改此值,双向数据绑定将在控制器中更新它。我在下面的plnkr上创建了一个例子。
angular
.module('snapshot', [])
.controller('snapshotCtrl', function(){
var sc = this;
sc.watchData = {
x : 0,
y: 0,
image: null
};
})
.directive('snapshot', function () {
return {
restrict: 'E',
scope: {
width: "=",
height: "=",
watchData: '='
},
template: '<button ng-click="mark($event)">Mark</button>',
link: function(scope, elem, attrs) {
console.log(scope.dataToWatch);
},
controller: function ($scope, $element) {
$scope.mark = function(event)
{
$scope.watchData.x = event.clientX;
$scope.watchData.y = event.clientY;
}
$scope.takeSnapshot = function()
{
var context = canvas.getContext("2d");
context.drawImage(video, 0, 0, $scope.width, $scope.height);
$scope.gotIt = true;
$scope.cameraOn = false;
$scope.setMarker = true;
$scope.watchData.image = canvas.toDataURL("image/jpeg");
}
}
}
});