Friday, March 28, 2014

ng-include dynamic change view and controllers

this story is a sample
when you want change view and controllers

this is a good example


<!DOCTYPE html>
<html>

  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script data-require="angular.js@1.0.7" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <style type="text/css" media="all">
      .controller-a {background-color: yellow;}
      .controller-b-style {background-color: lightgrey;}
    </style>
  </head>

  <body data-ng-app="webApp">
    <h1>Hello Plunker!</h1>
    <div class="controller-a" ng-controller="ControllerA">
      Controller A
      <div>
        <button ng-click="cntPlusPlus()">cnt++</button> CNT: {{cnt}}
      </div>
      <button ng-click="addB()">Add B</button>
      <div ng-repeat="B in Bs">
       <div ng-include="B.name"></div>
      </div>
    </div>
    <script type="text/ng-template" id="b-template">
   
      <div ng-controller="ControllerB">this is controller b: <button ng-click="cntPlusPlus()">cnt++</button></div>
    </script>
    <script>
      var webApp = angular.module("webApp",[]);
   
      webApp.controller("ControllerA", function($scope){
        $scope.cnt = 0;
        $scope.cntPlusPlus = function(){
          $scope.cnt++;
        };
     
        $scope.Bs = [];
        $scope.addB = function(){
          $scope.Bs.push({name:'b-template'});
        };
      });
   
      webApp.controller("ControllerB", function($scope){
        $scope.cntPlusPlus = function(){
          console.log("overwrite plus plus");
         // $scope.$parent.$parent.$parent.cnt++;  //should be moved to service
         alert('요소');
        }
      });    
    </script>
  </body>
</html>

No comments:

Post a Comment