Angular JS更改指令控制器的属性

时间:2015-11-14 12:55:01

标签: angularjs angularjs-directive angularjs-scope

我正在尝试从指令更改控制器的布尔属性。它设置为true,但是当我将其设置为false时,它应该显示其他html模板。她是我的代码:

指令代码:

app.directive('entityTaskList', function(){
     return {
     restrict: 'E',
     templateUrl: 'views/task/taskList.html',
     scope: {
         taskItems: '='
     },
     bindToController: true,
     controller: 'TasksCtrl as taskCtrl',
     link: function(scope, element, attrs){
         scope.openItem = function(){
             console.log("Open Items");
             var ctrl = scope.taskCtrl;
             ctrl.newTask = false;
         };
     }
   };
});

TaskCtrl代码:

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

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

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

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

    return $scope.TasksCtrl = this;

}]);

taskList.html

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

和task.html

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

        </div>
    </div>
    </div>

1 个答案:

答案 0 :(得分:1)

如果你改变了这个:

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

对此(字面意思):

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

你的代码会起作用,这是因为你使用了TaskCtrl的controllerAs语法,但没有将它分配给$ scope