2

我正在使用注入服务的指令。当数据从服务更改时,我希望更新指令。AngularJs刷新数据更改指示

我知道我需要使用$watch,但我不确定如何在我的情况下实施它。

我已经尝试了两种情况,但他们没有工作。以下是我的指示。

有人可以告诉我如何在$watch中添加如何在数据更改时更新指令吗?

app.directive('googleAnalytics', function(configFactory){ 
    return { 
    restrict: 'E', 
    replace: true, 
    link: function(scope,element,attrs){ 
     configFactory.getconfigs().then(function(configs) { 
     scope.gid = configs[0].ga_id; 
     var scriptTag = angular.element(document.createElement("script")); 
      scriptTag.text("ga('create', '"+scope.gid+"', 'auto');") 
      element.append(scriptTag); 
     }); 
    } 
    }; 
}) 

回答

1

使用$watch承诺是相当成问题。我从来没有正常工作,所以我建议你在你的服务中使用$broadcast来通知听众有任何改变。或者您可以轻松实现自己的轻量级观察者行为。

的JavaScript

angular.module('app', []) 
    // configFactory 
    .factory('configFactory', function($q, $interval) { 
    var config = null; 
    var callbacks = []; 

    // mock changes in configuration 
    $interval(function() { 
     function getTicks() { 
     return (new Date()).getTime(); 
     } 

     config = getTicks(); 
     angular.forEach(callbacks, function(callback) { 
     callback(config); 
     }); 
    }, 1000); 

    // factory impl  
    return { 
     // get resolved config promise 
     getConfig: function() { 
     return $q.when(config); 
     }, 
     // register callbacks 
     register: function(callback) { 
     var index = callbacks.indexOf(callback); 
     if (index === -1) { 
      callbacks.push(callback); 
     } 
     }, 
     // unregister callbacks 
     unregister: function(callback) { 
     var index = callbacks.indexOf(callback); 
     if (index === -1) { 
      callbacks.splice(index, 1); 
     } 
     } 
    }; 
    }) 

    // directive  
    .directive('directive', function(configFactory){ 
    return { 
     restrict: 'E', 
     replace: true, 
     template: '<div>{{ config }}</div>', 
     link: function(scope) { 
     // get initial value 
     configFactory.getConfig().then(function(config) { 
      scope.config = config; 
     }); 

     // callback fn 
     var callback = function(config) { 
      scope.config = config; 
      console.log(config); 
     }; 

     // register callback    
     configFactory.register(callback); 

     // when scope is destroyed, unregister callback 
     scope.$on('$destroy', function() { 
      configFactory.unregister(callback); 
     }); 
     } 
    }; 
    }); 

模板

<body> 
    <directive></directive> 
</body> 

在这里看到相关plunker https://plnkr.co/edit/ZVyLPm

+0

你去那里...... –

+0

谢谢我标记你的答案是正确的,并我感谢你的帮助。当我查看我的问题时,看起来我最大的问题不是更新价值,而是一旦调用了Google Analytics(分析)。当配置文件更改并且GA ID更新时,我需要重新初始化Google分析代码 – Jason