controller directive 数据传输

html 代码片段

<body>
    <div ng-controller="boxController">
      <box>滑动加载</box>
    </div>
  </body>

controller 代码片段

boxApp.controller('boxController', ['$scope',function($scope) {	  
	  $scope.loadData = function(){
	   		console.log("数据加载中。。。。");
	  };
	}]);

directive 代码片段

boxApp.directive("box", ["$timeout",function($timeout) {
    return {
        restrict: 'E',
        link: function(scope, element, attrs) {
            element.bind('mouseenter', function() { 
                // scope.loadData();
                 scope.$apply("loadData()");
            });
   }; 
}]);


这个地方,不能用独立scope,否则会报错,不能找到指定的函数


directive在不同controller中使用,假如有 boxController2,如何根据不同的controller调用不同的方法,需要给directive定义属性

此页面定义了howToLoad属性

html代码片段

    <div ng-controller="bomController">
      <bom  howToLoad="loadData()"></bom>
    </div>

    <div ng-controller="bomController2">
      <bom howToLoad="loadData2()"></bom>
    </div>

controller 代码片段

boxApp.controller('boxController', ['$scope',function($scope) {
	  $scope.loadData = function(){
	   		console.log("数据加载中。。。。");
	  };
	}]);

boxApp.controller('boxController2', ['$scope',function($scope) {
	  $scope.loadData2 = function(){
	   		console.log("数据加载中2222。。。。");
  };
}]);

directive 代码片段

boxApp.directive("box", ["$timeout",function($timeout) {
    return {
        restrict: 'E',
        link: function(scope, element, attrs) {
            element.bind('mouseenter', function() { 
                // scope.loadData();
                 scope.$apply(attrs.howtoload);
            });
   }; 
}]);

directive 代码需要注意 attrs.howtoload 要全部小写,如果在html中按照驼峰法则howToLoad来写的话,为了避免错误,可以全部采用小写的格式,不要忘记atrrs,不要加括号。

结果



参考 慕课网 Angularjs 实战

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值