您有两种可能的方式来实现这一目标。一种是在控制器中针对您传递到指令隔离范围的变量创建一个监视语句。
// code in view controller
$scope.sliderValue = 0;
$scope.$watch('sliderValue', function(newValue) {
if (angular.isDefined(newValue)) {
// Do stuff with new slider value
}
});
请注意,我们需要isDefined,因为每个手表都会在初始值未定义的范围编译时触发。
另一种方法是使用参数增强指令,该参数在滑块值更改时进行评估(很像回调函数)。
// sample directive code
angular.module('my-ui-controles', []).directive('mySlider', [function() {
return {
template: '...',
scope: {
value: '=mySlider',
onChange: '&'
},
link: function(scope, elem, attrs) {
// assume this is called when the slider value changes
scope.changeValue = function(newValue) {
// do other internal stuff and notify the outside world
scope.onChange({value: newValue});
}
}
}
}])
现在您可以像这样在模板中使用它:
<div my-slider="sliderValue" on-change="doStuff(value)"></div>
现在发生的情况是,一旦滑块值发生变化,我们就会评估传递给指令的 onChange 表达式。 doStuff 中的值填充了您的新滑块值。我们传递给onChange 的对象实际上是评估表达式的范围,doStuff 可以是控制器中的任何方法。
主要的好处是你有在你的指令中通知某人的逻辑,而不是通过一个手表在你的控制器中隐式通知。
希望这能让你朝着正确的方向前进。