Angularjs在链接点击后更改视图模板

时间:2015-11-28 12:28:41

标签: angularjs angularjs-directive angularjs-scope angular-controller

我想在点击链接后更改html模板。值为布尔值,初始值为true且加载了适当的模板,但是当值更改为false时,未加载新模板,我不知道原因。当boolean的初始值为true时,其他模板成功加载,但是在名为not的方法上加载。请帮忙。 这是我的代码:

TaskCtrl

app.controller('TasksCtrl', ['$scope', 'TaskService', function ($scope, TaskService) {
    // initialize function
    var that = this;
    that.newTask = true;
    that.name = "My name is Nedim";

    that.templates = {
        new: "views/task/addTask.html",
        view: "views/task/viewTask.html"
    };

    // load all available tasks
    TaskService.loadAllTasks().then(function (data) {
        that.items = data.tasks;
    });

    $scope.$on('newTaskAdded', function(event, data){
        that.items.concat(data.data);
    });

    that.changeTaskView = function(){
        that.newTask = false;
        console.log("New task value: " + that.newTask);
    };

    return $scope.TasksCtrl = this;

}]);

task.html

<!-- Directive showing list of available tasks -->
<div class="container-fluid">
<div class="row">
    <div class="col-sm-6">
        <entity-task-list items="taskCtrl.items" openItem="taskCtrl.changeTaskView()"></entity-task-list>  
    </div>
    <div class="col-sm-6" ng-controller="TaskDetailCtrl as taskDetailCtrl">
        <!-- form for adding new task -->
        <div ng-if="taskCtrl.newTask" ng-include="taskCtrl.templates.new"></div>
        <!-- container for displaying existing tasks -->
        <div ng-if="!taskCtrl.newTask" ng-include="taskCtrl.templates.view"></div>

    </div>
</div>

entityList指令

app.directive('entityTaskList', function () {
return {
    restrict: 'E',
    templateUrl: 'views/task/taskList.html',
    scope: {
        items: '='
    },
    bindToController: true,
    controller: 'TasksCtrl as taskCtrl',
    link: function (scope, element, attrs) {
    }
};

});

指令模板

<ul class="list-group">
<li ng-repeat="item in taskCtrl.items" class="list-group-item">
    <a ng-click="taskCtrl.changeTaskView()">
        <span class="glyphicon glyphicon-list-alt" aria-hidden="true"> </span> 
        <span>{{item.name}}</span>
        <span class="task-description">{{item.description}}</span>
    </a>
</li>

{{taskCtrl.newTask}}

1 个答案:

答案 0 :(得分:4)

没有任何plunker或JSFiddle我无法确定,但它可能与ng-include有关。我想到了两个解决方法。

首先我认为更好。仅使用1 <entity-task-list items="taskCtrl.items" openItem="taskCtrl.changeTaskView('view')"></entity-task-list> ... <div ng-include="taskCtrl.currentTemplate"></div> 并仅更改模板。

<强> HTML:

that.currentTemplate = that.templates.new;
...
that.changeTaskView = function(template) {
    that.currentTemplate = that.templates[template];
};

<强> JS:

ng-show

如果您不喜欢此解决方案,请尝试使用ng-if代替ng-show。使用display: none;时,元素将在页面加载时使用ng-if属性呈现,而true则在传递的值为Private Sub Document_Open() .... Dim strInput As String strInput = ActiveDocument.Content .... 时呈现它们。

希望这会对你有所帮助。