我想隐藏或显示一对元素,具体取决于照片数据是否可用。在初始页面加载时,这可以正常工作,但是,如果通过指令中的capturePhoto方法添加照片,我必须重新加载页面以使元素显示/隐藏。
html的
<button ng-hide="measurement.photo != ''" class="btn btn-default" ng-click="capturePhoto(measurement)">Photo</button>
<img ng-show="measurement.photo != ''" id="{{measurement.__id}}" src="{{measurement.photo}}" width="100" height="100"/>
的.js
.directive( 'sidingMeasurementGroup', function( $spawn, $measurementGroups, $compile, $projects, $filter, $photo )
{
return {
scope:
{
group: "=",
measurementTarget: "="
},
restrict: 'E', // E = Element, A = Attribute, C = Class, M = Comment
templateUrl: 'partials/directives/siding-measurement-group.html',
transclude: true,
replace:true,
link: function( $scope, iElm, iAttrs, controller )
{
$scope.capturePhoto = function(measurement)
{
function fail( e )
{
$error.
throw ( 'problem taking photo', e );
}
function success( imageURI )
{
cordova.exec(
function callback(data) {
measurement.photo = data.filePath;
var image = document.getElementById(measurement.__id);
image.src = null;
image.src = measurement.photo;
},
function errorHandler(err) {
alert('Error');
},
'CopyFiles',
'copyFileFromTmp',
[ imageURI ]
);
}
$photo.takePhoto( success, fail );
}
}
};
})
如果我在设置后记录了measurement.photo的值,则会显示正确的值,但在HTML端,元素不会更改其可见性。如何让他们对我指令中发生的变化做出反应?
答案 0 :(得分:2)
你试过范围。$ apply();
编辑添加:
这非常有效,这是我使用scope.$apply()
.directive( 'sidingMeasurementGroup', function( $spawn, $measurementGroups, $compile, $projects, $filter, $photo )
{
return {
scope:
{
group: "=",
measurementTarget: "="
},
restrict: 'E', // E = Element, A = Attribute, C = Class, M = Comment
templateUrl: 'partials/directives/siding-measurement-group.html',
transclude: true,
replace:true,
link: function( $scope, iElm, iAttrs, controller )
{
$scope.capturePhoto = function(measurement)
{
function fail( e )
{
$error.
throw ( 'problem taking photo', e );
}
function success( imageURI )
{
cordova.exec(
function callback(data) {
$scope.$apply(function () {
$scope.photoTaken = true;
measurement.photo = data.filePath;
var image = document.getElementById(measurement.__id);
image.src = null;
image.src = measurement.photo;
});
},
function errorHandler(err) {
alert('Error');
},
'CopyFiles',
'copyFileFromTmp',
[ imageURI ]
);
}
$photo.takePhoto( success, fail );
}