【问题标题】:Angular model doesn't update after ng-clickng-click 后 Angular 模型不更新
【发布时间】:2017-11-15 06:43:03
【问题描述】:

ng-repeat 模型在用户单击提交后不会更新,它只会在刷新时显示,我查看了类似的 problem,但我无法连接这些点。一位用户建议我做一个 ng-init,但我认为我做得不对。

使用 ng-init 它不显示任何数据,没有 ng-init 并删除它显示帖子的角度函数,但在单击后不更新模型。

注意:尖括号被替换,因为 laravel Blade 不喜欢它

html

    <div id="mypost" class="col-md-8 panel-default" ng-init="getPosts()" ng-repeat="post in myposts">
        <div id="eli-style-heading" class="panel-heading"><% post.title %></div>
            <div class="panel-body panel">
                <figure>
                    <p> <% post.body %></p>

                </figure>
            </div>


    </div>

Main.js

// this doens't show posts when i use ng-init
$scope.getPosts = function(){

    $http.get('/auth/posts').then(function(data){
        $scope.myposts = data.data;
    });



};

// this shows posts without ng-init but doesn't update when a user adds data


$http.get('/auth/posts').then(function(data){
    $scope.myposts = data.data;
});

再次更新

网络错误

PostController.php

public function storePost(Request $request)
{
    $data = request()->validate([
     'title' => 'required|max:120',
     'body' => 'required|max:1000'
    ]);

    $data['user_id'] = auth()->user()->id;

    $post = Post::create($data);


    // return redirect('/home')->withMessage('A new post was created.');

    return Response::json(array('success' => true));
}

【问题讨论】:

  • angular 不理解刀片语法。如果 Laravel 在 mustache 语法上抛出错误,请考虑使用 ng-bind
  • 您是否尝试在将数据分配给$scope.myposts 后添加$scope.$apply();?问题是承诺解决方案在 Angular 的摘要周期之外,所以它不知道它需要刷新 UI,除非你告诉它。
  • @SteveDanner ng-bind 不起作用,我仍然无法看到帖子。
  • @Lex 我试过了,还是看不到帖子
  • 如果我删除了获取帖子功能,并将其保留为$http.get('/auth/posts').then(function(data){ $scope.myposts = data.data; }); 并删除 ng-init,我可以看到帖子,但再次发布后它不会更新

标签: php angularjs


【解决方案1】:

不要使用 ng-init,除非您将 ng-repeat 的特殊属性(如 $last$even 用于嵌套的 ng-repeat )别名化。如果您希望一个函数立即触发,只需在它定义的控制器或服务/工厂中调用它。

https://jsfiddle.net/xf20j22u/1/

var app = angular.module('eli', []);

app.config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');
});

app.controller('mainCtrl', function($scope, $http, $timeout){
	$scope.posts = {};
  $scope.myposts = [{title:"titillating title",body:"Hot boddy"}]
	$scope.addPost = function(){
  
		$http.post('/auth/post', {
			title: $scope.post.title,
			body: $scope.post.body

		}).then(function(data, status, headers, config){
			$scope.posts.push(data);	
		
		});

	};

	$scope.getPosts = function(){

		$timeout(function(){
          debugger;
          $scope.myposts = [{title:"something new",body:"It's my body"}]
        },3000)
		//$http.get('/auth/posts').then(function(data){
		//	$scope.myposts = data.data;
		//	$scope.$apply();
		//});
	};
  $scope.getPosts();



});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.js"></script>
<div  ng-app="eli" ng-controller="mainCtrl">
  
  <div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts">
    <div id="eli-style-heading" class="panel-heading">
      <% post.title %>
    </div>
    <div class="panel-body panel">
      <figure>
        <p>
          <% post.body %>
        </p>

      </figure>
    </div>
  </div>
</div>

上面的工作版本可以用 $http 替换 $timeout 他们都为你调用 $apply 所以不要再调用它(只需要调用 $apply 如果你自己编写异步工作的东西然后更新模型和你想要触发视图刷新,角度事件处理程序和服务会为您完成)

【讨论】:

  • 谢谢你一定会记住这一点,但这仍然不能解决我的问题。我可以在没有 ng-init 的情况下检索帖子,但它不会在用户尝试添加帖子时更新。
  • 想想 ng-bind 和事情只是碍事了,真的不能确切地说出了什么问题,因为我必须添加一些上下文来让 ng-app 和控制器在那里运行,而不是timeout 可以使用 $http,$http 和 $timeout(以及像 ng-click 之类的所有处理程序)都会在后台为您调用 $apply。
  • 感谢您的努力,但我仍然遇到同样的问题,用户可以添加帖子,但它只是不更新​​(ajax 方式)只有在刷新时才会显示新数据,生病了,但它并没有解决我的问题。
  • 没问题:)。在成功回调中删除 debugger; 语句,并确保它确实调用将项目推送到数组中,如果不检查网络选项卡以查看响应是否为 200 OK 或其他内容
  • @OwlMan shaunhusain 早些时候说过。未调用您的回调,因此数组未更新,因为您从未输入回调。
【解决方案2】:

在另一个@Sorikairo 的帮助下,我们能够解决问题,我不想发布答案,因为我很懒,但我需要帮助那些在使用 laravel 时遇到非常类似问题的人。这是更新后的代码。

Main.js

var app = angular.module('eli', []);

app.config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');
});

app.controller('mainCtrl', ['$scope', '$http', function($scope, $http){


    $scope.posts = {};

    $scope.addPost = function(){

        $http.post('/auth/post', {
            title: $scope.post.title,
            body: $scope.post.body

        }).then(function(data, status, headers, config){
            console.log(data);  
            $scope.myposts.push(data.data);


        });

        $scope.post.title = '';
        $scope.post.body = '';

    };

    $scope.getPosts = function(){

        $http.get('/auth/posts').then(function(data){
            $scope.myposts = data.data;
        }).then(function(data, status, header, config){
        });



    };


    $scope.getPosts();





}]);

我需要添加

我的 php 文件的响应类

<?php

namespace App\Http\Controllers;

use App\Post;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function storePost(Request $request)
    {
        $data = request()->validate([
         'title' => 'required|max:120',
         'body' => 'required|max:1000'
        ]);

        $data['user_id'] = auth()->user()->id;

        $post = Post::create($data);

        $response = new Response(json_encode($data));
        $response->headers->set('Content-Type', 'application/json'); 


        // return redirect('/home')->withMessage('A new post was created.');

        return $response;
    }

现在可以了,谢谢大家

【讨论】:

    猜你喜欢
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多