$ rootscope。$ watch没有被触发

时间:2015-03-14 17:22:17

标签: angularjs angularjs-scope angularjs-watch

我在服务中设置了一个手表(下面的代码片段),我无法弄清楚为什么它没有被触发。在控制器中设置类似的手表(使用$ Scope。$ watch)当对象发生变化时会触发。

我错过了什么?

(function() {
    'use strict';
    angular
        .module('evidentia')
        .service('srcPaneSvc', SourcePaneSvc);

    SourcePaneSvc.$inject = ['$rootScope', '$timeout', 'dataProvider', 'dialogSvc', 'attachSvc'];

    function SourcePaneSvc($rootScope, $timeout, dp, ds, attachSvc) {

        var svc = this;
        svc.status =
        {
            isDirty : false,
            disabled : true,
            original : null
        };

        svc.attachSrc = attachSrc;
        svc.cloneSource = cloneSource;
        svc.deleteSource = deleteSource;
        svc.dirty = dirty;
        svc.editAttachment = editAttachment;
        svc.linkOriginal = linkOriginal;
        svc.newSource = newSource;
        svc.openAttach = openAttach;
        svc.openEditor = openEditor;
        svc.saveSource = saveSource;
        svc.showTemplates = showTemplates;
        svc.srcBox = openFSSrcBox;
        svc.openSrcDetail = openSrcDetail;
        svc.unattach = unattach;
        svc.unlink = unlink;

        $rootScope.$watch('dp.source', onSourceChange, true);

        function onSourceChange() {
            if (dp.source.id) {
...

此代码被触发......

(function() {
    'use strict';
    angular
        .module('evidentia')
        .controller('rightSidebarCtrl', RightSidebarCtrl);

    RightSidebarCtrl.$inject = ['$scope', '$window', '$timeout', '$location', 'dataProvider', 'syncSvc'];

    function RightSidebarCtrl($scope, $window, $timeout, $location, dp, ss) {

        var vm = this;
        vm.online = false;
        vm.auth = ss.isAvailable();
        vm.srcMode = true;
        vm.srcFilter = '';
        vm.wrapStyle = (dp.GO.wrap ? {'white-space': 'normal'} : {'white-space': 'nowrap'});

        vm.collapse = collapse;
        vm.toggleSrc = toggleSrc;
        vm.subClick = subClick;
        vm.srcClick = srcClick;
        vm.refClick = refClick;

        $scope.$watch('dp.source', function () {
            _ev.dbg('RightSiderBarCtrl: source changed.');
...

1 个答案:

答案 0 :(得分:1)

对我来说,看起来你想要观看的变量不在AngularJs范围内,据我所知它在这种情况下不起作用。有关说明,请参阅this question

您需要做的是触发摘要周期以使其发挥作用。

修改

添加到范围应解决问题:

$rootScope.db = db;