2015-07-31 6 views
1

Я заполняю свой шаблон с именем commentRecipe.html с данными.Угловая: обновить значение в директиве

И я могу позвонить controller.add(1,2,'comment here') изнутри шаблона.

Элемент обновляется в db и возвращает мой новый результат.

Вопрос является: Как я могу обновить экс mhRecipeId с полученными данными.

var app = angular.module('myApp'); 

app.directive('mhCommentRecipe', ['$log', 'commentService', function ($log, commentService) { 

     var commentController = function() { 
      var that = this; 

      that.add = function (commentId, recipeId, commentText) { 
       if (recipeId && commentText.length > 0) { 
        var resultObj = commentService.add(commentId, recipeId, commentText); 
       } 
      }; 
     } 

     return { 
      restrict: 'A', 
      templateUrl: '/app/templates/commentRecipe.html', 
      scope: { 
       mhRecipeId: '=', 
       mhCommentId: '=', 
       mhCommentText: '=' 
      }, 
      controller: commentController, 
      controllerAs: 'controller' 
    } 
    }]); 
(function() { 

    app.factory('commentService', [ 
     '$log', 'httpService', function ($log, httpService) { 

      var baseEndpointPath = '/myRecipes'; 

      return { 
       add: function (commentId, recipeId, commentText) { 

        $log.debug(commentId, 'c'); 

        var data = { 
         commentId, 
         recipeId, 
         commentText 
        } 

        var promise = httpService.post(baseEndpointPath + '/comment', data); 

        promise.then(function (response) { 
         // added 
        }, 
         function (error) { 
          $log.error(error); 
         }); 
       }, 

       remove: function (commentId) { 

        if (commentId) { 

         var data = { 
          commentId, 
          recipeId, 
          commentText 
         } 

         data.commentId = commentId; 

         var promise = httpService.post(baseEndpointPath + '/removeComment', data); 

         promise.then(function (response) { 
          $log(response, 'removed response'); 
         }, 
         function (error) { 
          $log.error(error); 
         }); 
        } 
       } 
      }; 
     } 
    ]); 

})(); 

app.factory('httpService', ['$http', '$q', 
    function ($http, $q) { 
     return { 
      get: function (endpoint) { 
       var deferred = $q.defer(); 

       $http.get(endpoint) 
        .success(function (response) { 
         deferred.resolve(response); 
        }) 
        .error(function() { 
         deferred.reject('Failed to fetch response from endpoint'); 
        }); 

       return deferred.promise; 
      }, 
      post: function (endpoint, data, config) { 
       var deferred = $q.defer(); 

       $http.post(endpoint, data, config) 
        .success(function (response) { 
         deferred.resolve(response); 
        }) 
        .error(function() { 
         deferred.reject('Failed to post data to endpoint'); 
        }); 

       return deferred.promise; 
      }, 
      put: function (endpoint, data, config) { 
       var deferred = $q.defer(); 

       $http.put(endpoint, data, config) 
        .success(function (response) { 
         deferred.resolve(response); 
        }) 
        .error(function() { 
         deferred.reject('Failed to put data to endpoint'); 
        }); 

       return deferred.promise; 
      } 
     }; 
    }]); 
+0

Является ли ваш комментарий 'commentService.add' обещанием? – Darren

+0

Даррен, нет, он возвращает результат обещания. –

ответ

0

решаемые проблемы, и я очень стесняюсь сказать решение! На мой взгляд, я просто использовал ex: mhRecipeId, когда я должен был использовать значение контроллеров.

+0

следующий раз напишите весь ваш код. это было бы решено гораздо быстрее. –

1

Вы размещаете значения, которые вы хотите отправить директивы в переменную:

// in controller 
that.mhRecipeId = whateverValueHere; 
that.mhCommentId = whateverValueHere; 
that.mhCommentText = 'comment text'; 

затем директивы в HTML вы бы поставил:

<mh-comment-recipe mh-recipe-id="controller.mhRecipeId" mh-comment-id="controller.mhCommentId" mh-comment-text="controller.mhCommentText"></mh-comment-recipe> 

Это проедет переменные в директиве для использования.

Если я не понял ваш вопрос :)

+0

Я думаю, вы не поняли мой вопрос, обновили мой текст, чтобы сделать его более понятным. –

+0

Вы сказали, что ваш сервис возвращает новый результат. Таким образом, вы заполняете this.mbRecipeId с вновь полученными данными. –

+0

Когда я смотрю на вашу демонстрационную функцию that.add. Я замечаю, что служба используется, но не привязана ни к чему. Возвращает ли служба результат? Если да, можете ли вы «var result = commentService.add (commentId, recipeId, commentText);' –

Смежные вопросы