Assign value in ng-include, without using the ng-click event?

1

In a controller B ("templates / menu_lateral.html"), I am generating dynamic content, in itself, I am generating a list and I add an ng-click and the class ".items", and from another controller A, It does not seem to recognize the function.

if I put this content in the A driver

$(document).on("click", ".items", function() {
    var valor=$(this).attr("include"); //tengo un attr llamado include con un valor para saber que template usar
    $scope.oIncludes={
      "tecnico": "templates/dashboard.html",
      "historia": "templates/historia_dos.html"
    }
    $scope.include=$scope.oIncludes[valor];
 })
 $scope.include="templates/dashboard.html";

By default, use the template, "templates / dashboard.html"; But with that click event, despite belonging to another controller, the class "items" is detected, but the ng-include, is never updated. What can I do?

This is the main controller template

<div ng-include="'templates/menu_lateral.html '"></div>
<div ng-include="include" ></div>
    
asked by unusuario 09.09.2016 в 20:11
source

1 answer

1

Do not do it, it's a bad idea. Never use jquery code mixed with angular, especially if it is an event.

Read link

If you want a general event for your application, create it in $rootScope and bindealo with ng-click where applicable.

The reason why it does not work for you is because the jQuery% click event does not notify the angular that there is a change in $scope and it does not update the view.

Here is an example that shows that the code works well if you use ng-click .

angular.module('app', [])
  .controller('IncludeCtrl', function($scope) {
    $scope.include = 'templates/dashboard.html';
    $scope.cambiaInclude = function() {
      $scope.include = $scope.include === 'templates/dashboard.html' ? 'templates/historia_dos.html' : 'templates/dashboard.html';
    }
  })
  .run(function($templateCache) {
    $templateCache.put('', '<h1>Nada<h1>');
    $templateCache.put('templates/dashboard.html', '<h1>Dashboard<h1>');
    $templateCache.put('templates/historia_dos.html', '<h1>Historia Dos<h1>');
    $templateCache.put('templates/menu_lateral.html', '<h1>Menu lateral<h1>');
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="IncludeCtrl">
  <button type="button" ng-click="cambiaInclude()">Cambiar</button>
  <div ng-include="'templates/menu_lateral.html'"></div>
  <div ng-include="include"></div>
</div>

You can use $scope.$apply to update the view but as the article referenced above says it is not something you should do.

    
answered by 12.09.2016 в 18:37