实时代码:Here
我已将名为FileTraversal
的服务添加到模块divkick.services
中。我还有一个模块divkick.container
和一个名为ContainerCtrl
的控制器。
我在ContainerCtrl
中添加了一个watcher函数,希望它可以监视FileTraversal.stuff
数组。
问题:我认为这是一个愚蠢的语法问题,如何从ContrainerCtrl
观看FileTraversal.stuff
主要应用程式:
(function () {
"use strict";
angular.module('divkick', [
'divkick.services',
'divkick.components',
'divkick.container'
]);
})();
控制器:
(function () {
angular
.module('divkick.container', [])
.controller('ContainerCtrl', ContainerCtrl)
ContainerCtrl.$inject = ['FileTraversal', '$scope', '$timeout'];
/* @ngInject */
function ContainerCtrl(FileTraversal, $scope, $timeout) {
/* jshint validthis: true */
var main = this;
activate();
////////////////
function activate() {
$scope.$watch(
// This function returns the value being watched. It is called for each turn of the $digest loop
function() { return FileTraversal.stuff; },
// This is the change listener, called when the value returned from the above function changes (but not working) :(
function(newValue, oldValue) {
if ( newValue !== oldValue ) {
console.log(newValue);
} else {
console.log('nope');
}
}
);
}
}
})();
服务:
(function () {
"use strict";
var fs = require('fs');
var glob = require("glob");
angular
.module('divkick.services', [])
.factory('FileTraversal', FileTraversal);
/* @ngInject */
function FileTraversal() {
var service = {
stuff: [],
check: check
};
return service;
////////////////
function check(filePath) {
glob(filePath + '/**/*{.png,.jpg,.gif}', function (er, files) {
if(er) return er;
service.stuff = files;
});
}
}
})();
我试过这样的watchcollection:
$scope.$watchCollection(
function() { return FileTraversal.stuff; },
function(newValue, oldValue) {
if ( newValue !== oldValue ) {
// Only increment the counter if the value changed
console.log(newValue);
} else {
console.log('nope');
}
}
);
最佳答案
尝试收藏手表而不是手表
$scope.$watchCollection(function () {
return FileTraversal.stuff;
}, function (newValue, oldValue) {
console.log("check")
if (newValue !== oldValue) {
console.log(newValue);
} else {
console.log('nope');
}
});
N:B:
您没有在小提琴中添加ng-controller的视图。可能是错字
JSFIDDLE