简体   繁体   中英

angular reloads controller when using a directive

My ui route has states like:

        .state('projects', {
            abstract: true,
            url: "/?username&token",
            templateUrl: "projects/views/Projects.html",
            controller: 'ProjectController'
        })
       .state('projects.mine', {
            url: "mine",
            templateUrl: 'projects/views/ProjectsMine.html'
        })
        .state('projects.all', {
            url: "all",
            templateUrl: 'projects/views/ProjectsAll.html'
        })

I made a directive:

    app.directive('description', function(){
        return{
            restrict: 'E',
            templateUrl : 'projects/views/directives/ProjectDescription.html',
            controller:ProjectController
        }
    });

I made two files exactly the same for the state templateUrls where the only difference is that the template of all uses the description directive like:

<description></description>

and the other one uses the content of the templateUrl for the description directive (copied 1on1) when not using the directive but the content of the templateUrl file the reload dosnt happen.

Everything works fine but when I go to the 'all' route the ProjectController gets reloaded. The directive looks like:"

<table>
  <tr >
      <td><b>name</b> </td>
      <td>{{project.name}}</td>
  </tr>
  <tr >
      <td><b>owner</b> </td>
      <td>{{project.owner}}</td>
  </tr>
<table>

the directive is added in an ng-repeat (in 'all' state) :

 <div ng-repeat="project in project|filter:searchText">
     <description></description>
 </div>

Links to states in my html:

    <a ui-sref=".mine()"><button>my projects</button></a>
    <a ui-sref=".all()"><button>all projects</button></a>

    <div ui-view></div>

the other one 'mine' uses the content of the directive and dosnt reload the controller. When going to 'all' from 'mine' a reload happens when I go from 'mine' to 'all' the controller isn't reloaded

How can I keep everything as it is but avoid the reload of the controller?

Removing

 controller:ProjectController 

fixed it, using controller:'controllerName' causes a controller to be created for every directive created.

您必须像函数调用一样链接到路由:

<a ui-sref=".list()" class="btn btn-primary">List</a> <a ui-sref=".paragraph()" class="btn btn-danger">Paragraph</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM