gpt4 book ai didi

javascript - 为什么我无法从 Controller 查看服务的属性?

转载 作者:行者123 更新时间:2023-12-03 08:44:39 26 4
gpt4 key购买 nike

实时代码:Here

我已将名为 FileTraversal 的服务注入(inject)到模块 divkick.services 中。我还有一个模块 divkick.container ,其 Controller 名为 ContainerCtrl

我在 ContainerCtrl 中添加了一个观察器函数,并希望它可以观察 FileTraversal.stuff 数组。

问题:我觉得这是愚蠢的语法问题,如何从 ContrainerCtrl 观看 FileTraversal.stuff

主应用程序:

(function () {
"use strict";
angular.module('divkick', [
'divkick.services',
'divkick.components',
'divkick.container'
]);
})();

Controller :

(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');
}
}
);

最佳答案

尝试收藏 watch 而不是 watch

$scope.$watchCollection(function () {
return FileTraversal.stuff;
}, function (newValue, oldValue) {
console.log("check")
if (newValue !== oldValue) {

console.log(newValue);
} else {
console.log('nope');
}
});

N:B:

您没有在 fiddle View 中添加 ng-controller 。可能是一个错字

JSFIDDLE

关于javascript - 为什么我无法从 Controller 查看服务的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32940922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com