我有一个指令来控制DOM中显示的图像:
summariesApp.directive('changePlus', function () {
return function changePlus(scope, element, attr) {
if (scope.$parent.Tab == "MultiVariant")
if (scope.$parent.multis[parseInt(attr.a)].show) {
element[0].src = 'Images/hide.png';
}
else {
element[0].src = 'Images/show.png';
}
}
else {
element[0].src = 'Images/show.png';
}
element.on('mousedown', function (event) {
var imgName = event.target.src.split("/");
if (imgName[imgName.length - 1] == 'show.png') {
event.target.src = 'Images/hide.png'
}
else {
event.target.src = 'Images/show.png'
}
});
}
});
问题是,当我调用服务时,我希望运行此指令。我认为通过使用 $scope.$apply 并触发摘要循环,将评估该指令,但事实并非如此。有什么方法可以让我使用 $scope.$apply 上的指令重新评估视图?
我想你正在寻找$scope.$watch:
$scope.$watch('myModelProperty', function() {
// do something
});
$scope.buttonClicked = function() {
$scope.myModelProperty = "foo"; // This will trigger $watch expression
};
但最佳做法是在服务上绑定指令的属性。尽可能避免使用$apply和$watch。
带属性 :
angular.module('myModule', []).directive('myDirective', function() {
return {
restrict: 'E',
scope: {
myVar: '=' // two ways data-binding
},
link: function(scope, element, attrs, controllers) {
scope.myVar //myVar is available in your scope and is bind to your model
},
templateUrl: 'my-template.html'// myVar is available in your template and is bind to your model
};
});