My note1

           Angular自定义指令和Controller间通信


Angular 不同的Controller之间通信,使用异步回调响应式通信—事件机制(或消息机制)。对,这就是angularjs解决controller之间通信的机制,所推荐的唯一方式,简而言之这就是angular way。

      Angularjs为在scope中为我们提供了冒泡和隧道机制,$broadcast会把事件广播给所有子controller,而$emit则会将事件冒泡传递给父controller,$on则是angularjs的事件注册函数,有了这一些我们就能很快的以angularjs的方式去解决angularjs controller之间的通信,代码如2:



1.



 
   
   
 
 
   


      Date format:

      Current time is:
   



      Expression:
     
     
     

           

  •          [ X ]
             {{expr}} =>
           

  •      

   

 



2.



 
   
   
 
 
   


name :      
   

   
Ctr1 name:


 



 



script.js

//自定义指令

function Ctrl2($scope){
$scope.format='M/d/yy h:mm:ss a';
}
angular.module('time',[]).
directive('myCurrentTime',function($timeout,dateFilter){
return function(scope,element,attrs){
var format,
timeoutId;


//used to update the UI
function updateTime(){
element.text(dateFilter(new Date(),format));
}


//watch the expression, and update the UI on change
scope.$watch(attrs.myCurrentTime,function(value){
format=value;
updateTime();
});
      // schedule update in one second
      function updateLater() {
        // save the timeoutId for canceling
        timeoutId = $timeout(function() {
          updateTime(); // update DOM
          updateLater(); // schedule another update
        }, 1000);
      }


      // listen on DOM destroy (removal) event, and cancel the next UI update
      // to prevent updating time ofter the DOM element was removed.
      element.bind('$destroy', function() {
        $timeout.cancel(timeoutId);
      });


      updateLater(); // kick off the UI update process.
}
});


function Cntl2($scope) {
  var exprs = $scope.exprs = [];
  $scope.expr = '3*10|currency';
  $scope.addExp = function(expr) {
     exprs.push(expr);
  };


  $scope.removeExp = function(index) {
    exprs.splice(index, 1);
  };
}

//进程间通信

angular.module("app", []).controller("parentCtr",


function ($scope) {
    $scope.$on("Ctr1NameChange",


    function (event, msg) {
        console.log("parent", msg);
        $scope.$broadcast("Ctr1NameChangeFromParrent", msg);
    });
}).controller("childCtr1", function ($scope) {
    $scope.change = function (name) {
        console.log("childCtr1", name);
        $scope.$emit("Ctr1NameChange", name);
    };
}).controller("childCtr2", function ($scope) {
    $scope.$on("Ctr1NameChangeFromParrent",


    function (event, msg) {
        console.log("childCtr2", msg);
        $scope.ctr1Name = msg;
    });
});

你可能感兴趣的:(My note1)