Home Angular model doesn't update after ng-click
Reply: 2

Angular model doesn't update after ng-click

BARNOWL
1#
BARNOWL Published in 2017-11-14 21:13:36Z

the ng-repeat model doesn't update after a user clicks submit, it will only show on refresh, i reviewed a similar problem, but i couldn't connect the dots. A user recommended i do a ng-init, but i don't think im doing it right.

with ng-init it shows no data, without ng-init and removing the angular function it shows posts but doesn't update the model after click.

note:the angular brackets are replaced because laravel blade doesn't like it

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;
});

Updated Again

network error

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));
}

shaunhusain
2#
shaunhusain Reply to 2017-11-14 21:57:04Z

Don't use ng-init except in cases where you are aliasing a special property of ng-repeat like $last or $even for nested ng-repeats. If you want a function to trigger immediately just call it in the controller or service/factory it is defined in.

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>

Working version above can replace $timeout with $http they both call $apply for you so don't call it again (only need to call $apply if you write your own things that async do work then update the model and you want to trigger a view refresh, angular event handlers and services do it for you)

BARNOWL
3#
BARNOWL Reply to 2017-11-14 22:43:03Z

With the help of another @Sorikairo we were able to solve the problem, i didn't want to post the answer because i was lazy, but i need to help the people who ever encounter a very similar problem when using laravel. Here is the updated code.

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();





}]);

i needed to add

the response class to my php file

<?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;
    }

it works now thank you everyone

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.569335 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO