当控制器中的范围更改时(在表单提交后),角度视图不会更新

时间:2015-04-08 01:22:45

标签: angularjs angularjs-directive angularjs-scope angularjs-controller

我对角度很新,所以我可能会说这一切都错了,但是这里有。我有一张表格

<form name="search_form" novalidate ng-submit="searchForm(search_form.$valid)" >
  <div class="maincontainer">
    <div class="formcontainer">What to eat?</div>
    <div class="formcontainer"><input type="text" name="food_type" ng-model="food_type" placeholder="Enter a search term" required></div>
    <div class="formcontainer">Where to look?</div>
    <div class="formcontainer">  <input type="text" name="cityname" ng-model="trader.cityname" value="cityname"  googleplace="" placeholder="Enter a location" required>
  </div>

  <div class="formcontainer">
    <button type="submit" class="btn-main2" >Submit</button>
  </div>
</form>

当我提交时,我想根据我从谷歌获取的位置获取结果并在新视图中显示

myControllers.controller('SearchCtrl',['$scope','Search','$location', function ($scope,Search,$location) {

  $scope.setSearchLocation = function(place){

    $scope.lat = place.geometry.location.lat();
    $scope.lng = place.geometry.location.lng();
  }

  $scope.searchForm = function() {
    // check to make sure the form is valid
    if (!$scope.search_form.$valid) {
      alert('Please fill out all fields');
    }
    else{
      $scope.results = Search.do_search($scope.lat,$scope.lng);
      $location.path('search-results');
    }
  };   

}])
.directive('googleplace', function() {
  return {
    require : 'ngModel',
    link : function(scope, element, attrs, model) {
      var options = {
          types : [],
      };
      scope.gPlace = new google.maps.places.Autocomplete(element[0],options);

      google.maps.event.addListener(scope.gPlace, 'place_changed',function() {
        var place = scope.gPlace.getPlace();
        scope.setSearchLocation(place);
        scope.$apply(function() {
          model.$setViewValue(element.val());  
        });
      });
    },

  };
});

除了视图在结果视图中不更新外,一切都按预期工作。如果我在$ scope.results外设置searchForm()函数,那么一切都正确呈现。我意识到这是因为它存在于页面呈现之前,只是说该部分有效。

当我尝试$ scope。$ apply()它说已经在进行中

<div id="results-container" ng-repeat="result in results">
        <div id="picbox"><img src="../images/test.jpg" alt="" "/></div>
          <div id="addressinfo">
            <h4>John's Restaurant  </h4>
            <p>123 York Street, Toronto ON <br>
              <span id="type">#
            Burgers, #Poutine</span></p>
          </div>
          <div id="location">4.2m<br>
            <img src="../images/heart.png" width="86" height="76" alt=""/><br>
          </div>
        </div>
      </div>

1 个答案:

答案 0 :(得分:1)

当你调用$location.path(...)时,控制器的$ scope对象总是被初始化。

我的建议是......

  1. div#results-container存在的同一模板上写下form[name=search_form]的元素。

  2. 删除$location.path('search-results');

  3. 我希望这可以帮到你。