0

Im trying to update my controller from a JSON that is generated from the server, the route provides the Id for the item I need that is fetched from a Database and saves it on the ProyectoId variable. When I first load the page everything works fine, but when I click on a link that takes me to the same page but different Id the third flag:

alert("Third");

and all the code that comes after that is not triggering. The AJAX result is being retrieved properly so that is not the issue. I've been banging my head against the wall for a while and I could not find any answers. The closest question I could find was this:

Angular page refresh on changing URL parameter in browser

But I couldn't get it to work and I don't think this is the same issue I'm having.

This is my app.module.js file (trimmed so that unnecesary parts do not appear):

(function () {
    var app = angular.module('my-app', ['ngRoute', 'proyecto-module']);


    app.config(['$locationProvider', '$routeProvider',
    function config($locationProvider, $routeProvider) {
        $locationProvider.hashPrefix('!');

        $routeProvider.
            when('/Home', {
                template: '<home></home>',
            }).
            when('/Proyecto/Index/:proyectoId', {
                template: '<proyecto-index></proyecto-index>',
            }).
            otherwise('/Home');
    }
    ]);
})();

This is my proyecto.module.js file (also trimmed):

(function () {
    var app = angular.module('proyecto-module', []);

    app.directive('proyectoIndex', ['$routeParams', '$route', function ($routeParams, $route) {
        return {
            restrict: 'E',
            templateUrl: '/Proyecto/Index/',
            controllerAs: 'ctrlProyectoIndex',
            controller: function () {
                var controller = this;
                this.ProyectoId = $routeParams.proyectoId;
                this.Nombre = "";
                this.Pedidos = [];

                var controllerScope = angular.element("proyecto-index").scope();
                var actualizarDatos = function () {
                    var token = $('input[name="__RequestVerificationToken"]').val();
                    var data = { __RequestVerificationToken: token, id: controller.ProyectoId };
                    $.ajax({
                        url: '/Proyecto/ProyectoJSON',
                        type: 'POST',
                        data: data,
                        success: function (result) {
                            alert("Second!");
                            controllerScope.$apply(function () {
                                alert("Third!"); //From this point forward none of the code is triggering.
                                controller.Nombre = result.Nombre;
                                controller.Pedidos = result.Pedidos;
                            });
                        },
                        error: function (xhr, status, error) {
                            alert("ERROR: " + xhr.responseText);
                        }
                    });
                };
                alert("First!");
                actualizarDatos();
            },
        }
    }]);
})();

And this is my HTML, you may notice some razor tags, since Im using ASP.NET MVC for the server code (you may notice some variables are missing since I trimmed the controller code):

<h1>Proyecto Index</h1>
<h2>Nombre Proyecto: {{ctrlProyectoIndex.Nombre}}</h2>
<a href="" ng-click="ctrlProyectoIndex.modalCrearPedido()">Crear Pedido</a>
<div>
    <a href="/WebApp#!/Proyecto/Pedido/{{item.PedidoId}}" ng-show="ctrlProyectoIndex.Pedidos.length > 0" ng-repeat="item in ctrlProyectoIndex.Pedidos">{{item.Titulo}}</a>
</div>


<div id="modal-crear-pedido" ng-show="ctrlProyectoIndex.modal">

    @using (Html.BeginForm("AgregarPedido", "Proyecto", FormMethod.Post, new { id = "frm-crear-pedido" }))
    {
        @Html.AntiForgeryToken()
        <input type="text" name="ProyectoId" ng-model="ctrlProyectoIndex.ProyectoId" />
        <span>Nuevo proyecto para: {{ctrlProyectoIndex.Nombre}}</span>
        <br />
        <input type="text" name="Titulo" placeholder="Titulo del pedido" />
        <br />
        <textarea name="Texto" placeholder="Descripción del pedido" ></textarea>

        <input type="submit" value="Aceptar" />
    }
</div>
<div id="fondo" ng-show="ctrlProyectoIndex.modal" ng-click="ctrlProyectoIndex.cerrarModal()"></div>

Im new to angularJS so any other pointers are always apreciated :)

Community
  • 1
  • 1
ifiora
  • 9
  • 3

1 Answers1

0

You should make changes to the model, then call $scope.$apply(). Also, explicityly inject $scope into the controller/directive.

Try:

success: function (result) {
   controller.Nombre = result.Nombre;
   controller.Pedidos = result.Pedidos;
   $scope.$apply();
},
Xun Chao
  • 82
  • 8