0

I have this directive which tries to watch for changes in a json object on scope. The JSON object is retrieved using a restangular based service, but somehow the $watch seems to be executed only once, logging 'undefined'.

The directive is used in the index.html of the app, so I suspect this has to do with the controller only working for the specific view or form...is there a way to get the directive to see those changes?

update: figured I could just call the TextsService from the directive itself, seems like a good solution to the problem. If anyone has better suggestions I'd welcome them still though.

service:

angular.module('main').service('TextsService', function(Restangular) {

    this.getTexts = function(jsonRequestBase, jsonRequest, callback) {

        Restangular.one(jsonRequestBase, jsonRequest).get().then(
            function(texts) {
                callback(texts);
            }
        );
    };
});

call in controller:

TexstService.getTexts("content", "file.json", function (texts) {
    $scope.mytest = texts;
});

directive:

app.directive('myDirective',
function() {
    return {
        restrict: 'A',
        templateUrl:'test.html',
        transclude: true,

        link: function(scope, elm, attrs) {

            scope.$watch('mytest', function(){
                console.log(scope.mytest);
            }, true);
4

3 回答 3

0

在接收变量之前使用 null 创建变量。也许这行得通。

于 2013-07-13T05:16:30.760 回答
0

问题是您的指令的范围不知道该mytest变量。定义指令时需要定义绑定:

app.directive('myDirective',
  function() {
    return {
      scope: {
        myDirective: '='
      },
      restrict: 'A',
      templateUrl:'test.html',
      transclude: true,
      link: function(scope, elm, attrs) {
        scope.$watch('myDirective', function(newVal){
            console.log(newVal);
        }, true);
    };
  }
);

这将获得分配给指令属性的任何变量并观察其值。

您在视图中的指令应如下所示,以将其绑定到“mytest”:

<div my-directive="mytest"></div>
于 2014-05-29T08:10:09.793 回答
0

我想我可以从指令本身调用 TextsService,这似乎是解决问题的好方法。如果有人有更好的建议,我仍然欢迎他们。

于 2013-07-12T10:36:27.213 回答