Angularjs 角度范围在$watch中未定义,范围变量在$animate函数中不可用
我有一个动画指令,它使用scope.$watch来侦听其属性的更改,在本例中是指令本身。问题是我需要从$watch或animation函数内部操纵父范围变量。在我的指令内部,但在watch外部,定义了scope、element和attrs参数。在$watch中,只定义元素,而不定义范围和属性Angularjs 角度范围在$watch中未定义,范围变量在$animate函数中不可用,angularjs,animation,angularjs-directive,angularjs-scope,ng-animate,Angularjs,Animation,Angularjs Directive,Angularjs Scope,Ng Animate,我有一个动画指令,它使用scope.$watch来侦听其属性的更改,在本例中是指令本身。问题是我需要从$watch或animation函数内部操纵父范围变量。在我的指令内部,但在watch外部,定义了scope、element和attrs参数。在$watch中,只定义元素,而不定义范围和属性 app.directive('animateGif', function ($animate) { return { restrict: 'A', link: function (sco
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年的建议,这在过去的enter animation函数中对我有效,但由于某些原因,我能够访问的范围不包含定义父范围的控制器的范围函数。如果您对此有任何建议,我们将不胜感激
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();
}
}
});
您可以使用$timeout服务和$scope.$apply在回调时编辑父作用域
$timeout(function() {
scope.$apply(function() {
scope.foo = "bar";
});
});