我试图有一个指令,当集合收到更新时更新,但似乎无法触发监视事件(或$watchCollection
)。
在我的工厂,我有一个收藏
var streams = {
"main":{ stream: streamDetails},
"guest":{ stream: streamDetails}
}
我通过
将其包含在我的 Controller 中.controller('vidCtrl', function($scope, vidFactory){
$scope.streams = vidFactory.streams;
});
在我的 html 中,我有
<stream data-name="main"></stream>
<stream data-name="guest"></stream>
<stream data-name="other"></stream>
管理视频的指令是
app.directive('stream', function(){
return {
restrict: 'E',
template: '<video></video>',
scope:{
name: '='
},
link: function(scope, element, attr){
if(!scope.streams[scope.name]) return console.log('video not ready');
var vid = scope.streams[scope.name];
var video = element.find('video');
video.attr('src', vid.stream);
video[0].play();
}
}
});
我想做的是将 other
流添加到 $scope.streams
中,然后让它显示在正确的标签中。
我希望在我的指令中添加
scope.$watchCollection('videos', function(){
//update stream somehow
});
但不幸的是,当我向视频对象添加新视频时,$watchCollection
没有被触发。
我通过以下函数添加到 vidFactory.videos
中,我可以验证该函数是否正确更新了集合。当然,在工厂中,我不能使用 $scope.$apply()
,如果我将 .on 方法放在 Controller 中,它会触发多次,因为 Controller 包含在一些不同的 Angular Directive(指令)。
qc.on('video:added', function(stream){
streams[stream.name] = stream;
});
我还尝试通过
观看特定流而不是$watchCollection
if(!scope.streams[scope.name]){
scope.streams[scope.name]=null;
scope.$watch(scope.streams[scope.name], function(){
//add video to stream method would go here
}, true);
我认为 using watch 优于 $watchCollection
,但我不明白为什么我的 Controller 没有触发 $watch
。
最佳答案
您正在尝试访问 scope.streams
,就好像它是在您的指令作用域中定义的一样。
但是,由于您的指令使用隔离作用域,因此它不会从其父作用域继承streams
。
您可以将其传递给指令,如下所示:
<stream data-streams="streams" data-name="other"></stream>
app.directive('stream', function () {
return {
restrict: 'E',
template: '<video></video>',
scope: {
streams: '=',
name: '@'
},
...
<小时/>
另请参阅此 short demo 。
关于javascript - 指令未在 watch(或 watchCollection)上更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24521003/