我有一个使用范围的动画指令。$ watch侦听对其属性的更改,在本例中是指令本身。问题是我需要从$ watch或动画函数内部操作父作用域变量。在我的指令中,但在监视之外,定义了scope,element和attrs参数。在$ watch内部,只定义了元素,而范围和attrs则没有。
app.directive('animateGif', function ($animate) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
// scope, element, and attrs are defined here
scope.$watch(attrs.animateGif, function(runAnim) {
// only element is defined here
if (runAnim) {
$animate.addClass(element, 'animLargenerGif', function() {
// a child scope is defined here
console.log("add class callback in directive");
});
} else {
$animate.removeClass(element, 'animLargenerGif', function() {
console.log("remove class callback in directive");
});
}
});
}
};
});
或者,我想在动画函数中操作父作用域。我在moo http://www.yearofmoo.com/2013/05/enhanced-animations-in-angularjs.html#using-scope-in-your-js-animations年找到了一些建议,过去在“输入”动画函数中对我有用,但由于某种原因,我能够访问的范围不包含范围函数定义父作用域的控制器。对此有任何建议将不胜感激。
app.animation('.animLargenerGif', function() {
var elm, $scope, parent;
var getScope = function(e) {
return angular.element(e).scope();
};
return {
addClass : function(element, className, done) {
$scope = getScope(elm).$parent;
elm = element[0];
setTimeout(function() {
$(elm).transition({ y: '-440px' }, 800, 'linear', function() {
setTimeout(function() {
$scope.animationSetter($scope.largenerObj.animElm); // this function is unavailable but the $scope.largenerObj is defined -- only if I call get scope inside of the timeout
$scope.$apply();
done();
}, 1000);
});
}, 0);
},
removeClass : function(element, className, done) {
console.log("class removed", className);
done();
}
}
});
答案 0 :(得分:0)
您可以使用$ timeout服务和$ scope。$ apply来编辑回调中的父范围
$timeout(function() {
scope.$apply(function() {
scope.foo = "bar";
});
});