10

单击链接后,我正在尝试更改 html 模板。value 是 boolean,初始值为 true 并加载了适当的模板,但是当 value 更改为 false 时没有加载新模板,我不知道原因。当 boolean 的初始值为 true 时,其他模板已成功加载,但在未调用的方法上。请帮忙。这是我的代码:

任务控制

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;

}]);

任务.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}}

4

1 回答 1

4

没有任何 plunker 或 JSFiddle 我无法确定,但它可能与ng-if. 我正在考虑两种解决方法。

首先,我认为更好。仅使用 1ng-include并且仅更改模板。

HTML:

<entity-task-list items="taskCtrl.items" openItem="taskCtrl.changeTaskView('view')"></entity-task-list>
...
<div ng-include="taskCtrl.currentTemplate"></div>

JS:

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

或者,如果您不喜欢此解决方案,请尝试使用ng-show而不是ng-if. withng-show元素会display: none;在页面加载时用属性渲染,而 with元素会ng-if在传递的值为true.

希望这对您有所帮助。

于 2016-01-30T08:36:05.657 回答