如何将值从一个控制器传递到另一个控制器? -angularjs

时间:2018-02-04 14:49:23

标签: angularjs

我从controller1中的函数获取值。我想将此值设置为controller2指令的模板。我很困惑如何在此范围内使用范围来实现相同目的。

HTML

<body ng-app = "myApp" ng-controller="parentcontroller as ctrl">
    <div class ="boardcanvas" style ="overflow-x:auto;"> 
        <div id = "board">
           <list-wrapper ng-repeat="task in ctrl.tasks track by $index" class ="listwrapper" id = "listwrapper"></list-wrapper>

            <add-list-controls class = "controls" tasks ="ctrl.tasks" ng-show ="ctrl.listcontrolarea"></add-list-controls>
        </div>
    </div>
</body>

Controller1及其指令:

angular.module('myApp')
.controller('listController', ['$scope','$compile','$http', function($scope, $compile, $http){
    'ngInject';

    $scope.tasks=[];
    $scope.cardarr =[]; 

    vm.addme = function(){
         console.log(vm);
         console.log($scope.tasks);
         $scope.tasks.push({title: $scope.title, cardarr: []});   
}
}])
.directive('addListControls', function() {
    return {
        restrict: 'E', // Element directive'
        controller: 'listController as listctrl2',
        scope: { tasks: "=",
                 cardarr: "="},
        template: `<textarea ng-model= "listctrl2.title" placeholder ="Add a List" id="input" style = "position:absolute"></textarea>
        <button id="controlbutton"  class ="btn btn success" style = "position:absolute" ng-click="listctrl2.addme()">Save
        </button>`,

};
});

Controller2及其指令:

.controller('listWrapperController', ['$scope','$compile','$http', function($scope, $compile, $http){
    'ngInject';

     $scope.tasks=[];

}])

.directive('listWrapper', function() {

    return {
        restrict: 'E', // Element directive
        scope:{
            tasks: '='
        },  
        controller: 'listWrapperController as listctrl',
        template: `<div id="titlebox">
        <b class ="card1" tasks="listctrl.task" id ="cardtitle">
            {{task.title}} // set the value from controller1 here
        </b>
    </div> `
};
});

1 个答案:

答案 0 :(得分:0)

您正在使用两个控制器上的$scope.tasks数组,这会覆盖由指令定义设置的原始$scope.task引用(ctrl.tasks)。

仅在undefined

时尝试评论或初始化
$scope.tasks= $scope.tasks || [];
$scope.cardarr = $scope.cardarr || []; 

必须更改listWrapper指令并将ng-repeat转换为其模板:

<强> HTML

<list-wrapper tasks="ctrl.tasks"></list-wrapper>

listWrapper指令

  (...)
 .directive('listWrapper', function() {
   return {
        restrict: 'E', // Element directive
        scope:{
            tasks: '='
        },  
        controller: 'listWrapperController as listctrl',
        template: 
         `<div id="titlebox" ng-repeat="task in tasks track by $index" class ="listwrapper" id = "listwrapper">
        <b class ="card1" id ="cardtitle">
            {{task.title}} // set the value from controller1 here
        </b>
    </div> `
};
});
相关问题