我有一个音频播放器,我正在使用这个范围滑块 - 效果很好。 https://github.com/danielcrisp/angular-rangeslider/blob/master/angular.rangeSlider.js
<li ng-controller="PlayerCtrl" style="display:inline-block;">
...
<span range-slider min="0" max="100" ng-controller="PositionCtrl" model-max="position" pin-handle="min" filter="positionSilderText">
...
</li>
所以我在PlayerCtrl中创建了一个新的Controller PositionCtrl,如下所示:
angular.module('myApp.controllers', []).controller('PlayerCtrl', ['$scope','$timeout',function($scope,$timeout) {
$scope.audioTag=document.getElementById('audioPlayer');// an <audio/> tag
$scope.position = 0;
$scope.PositionCtrl = function ($scope) {
$scope.$watch('position', function() {
if (updatePlayPosition && $scope.audioTag.duration) {
$scope.audioTag.currentTime = $scope.audioTag.duration * $scope.position / 100.0;
}
updatePlayPosition=true;
});
};
...
$scope.ui=function() {//called by a $timeout
...
var newpos = $scope.audioTag.duration;
$scope.position = setpos;
// $scope.$$childHead.position = setpos;// <<-- dont want to do this
....
}
});
所以最初ui()函数使用$ scope.position更新我的滑块pos并且一切都很好。
我的问题是,一旦我拖动滑块,就会在子(PositionCtrl)范围内创建位置变量,因此手表不再在父(PlayerCtrl)范围内找到变量。因此,滑块不再从ui()方法更新。
如果我取消注释该行以分配$$ childHead.position,则观察者可以正常工作。但它并不好,因为我可能会在以后添加更多的孩子和AFAIK你无法从父母访问子范围(不知道为什么)。
与两个范围共享职位的正确方法是什么?
答案 0 :(得分:1)
我认为这可能再次成为继承问题。查看继承文章:https://github.com/angular/angular.js/wiki/Understanding-Scopes。希望这会有所帮助。我认为这可能归结为你想要在一个对象(而不是$ scope.position,做$ scope.someClevelModelName.position)中放置你想要观察的东西,并观察THAT属性而不是外部范围的position属性。
真的希望这有帮助。
(在这里发布SO)
答案 1 :(得分:0)
您可以随时使用$scope.$parent
,或者如果您不想,可以在父作用域中定义一个函数来更新所需的变量,然后从子作用域内调用它
app.controller('Parentctrl',function($scope) {
$scope.position= 1;
$scope.changePosition = function(p) {
$scope.position= p;
};
$scope.PositionCtrl = function ($scope) {
$scope.$watch('position', function() {
if (updatePlayPosition && $scope.audioTag.duration) {
$scope.audioTag.currentTime = $scope.audioTag.duration * $scope.position / 100.0;
}
updatePlayPosition=true;
$scope.changePosition(5);
});
};
});
我希望这就是你需要的东西
答案 2 :(得分:0)
在这里得到了答案: https://groups.google.com/forum/#!topic/angular/eY1H2O7-vfg
我只需将位置变量放入父范围内的对象中。
即。使用$ scope.data.postion并在子范围内观察data.position。
这里有信息: https://github.com/angular/angular.js/wiki/Understanding-Scopes