簡體   English   中英

如何將一個控制器的值傳遞給另一控制器? -angularjs

[英]How to pass a value from one controller to another controller? -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> `
};
});

您將在兩個控制器上$scope.tasks數組,並且此數組將覆蓋由指令定義設置的原始$scope.task參考( ctrl.tasks )。

嘗試注釋或僅在undefined初始化

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

必須更改listWrapper指令,並將d 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> `
};
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM