controller 调用指令内部的方法

在工作中,遇到一个问题,写了一个分页插件(指令),

<input type="text" ng-model="countObj"/>
<div>{{count}}</div>

<div>
    <button ng-click="addCount1()" class="add">add</button>
</div>
<div>
    <button ng-click="minuseCount1()" class="minuse">minuse</button>
</div>
<div huangbiao count-obj="count"></div>
<br>
<br>
{{count}}
<br>
<button ng-click="addCount()" class="addCount">addCount</button>
<button ng-click="minuseCount()" class="minuseCount">minuseCount</button>
/**
 * 定义常量WAP_CONFIG;WAP为当前子模块功能
 * */
angular.module('klwkOmsApp')
		.config(["$stateProvider","$urlRouterProvider",function ($stateProvider, $urlRouterProvider) {
			// 如果没有匹配的路径,则设置默认路径
			$urlRouterProvider.otherwise('/index');
			$stateProvider
				//首页
				.state('index',{
					url: '/index',
					templateUrl:'controllerDirectiveTemp.html',
					controller:'AccordionDemoCtrl'
				})
		}]);

angular.module("klwkOmsApp")
		.directive('huangbiao',function() {
			return {
				restrict: 'A',
				controller: function($scope){
					var currentController = this;

					$scope.addCount1 = function(){
						$scope.countObj++;
					};

					$scope.minuseCount1 = function(){
						$scope.countObj--;
					};

					currentController.countChangeAction = function(){
						console.log("我是指令内部方法 countChangeAction : " + $scope.countObj);
//                            console.log(countChangeAction);
					};

					$scope.$watch("countObj",function(){
						currentController.countChangeAction();
					});
				},
				scope : {
					countObj : '='
				},
				templateUrl: 'huangbiaoDirective.html',
				compile: function compile(tElement, tAttrs, transclude) {
					return {
						pre: function preLink(scope, iElement, iAttrs, controller) {
						},
						post: function postLink(scope, iElement, iAttrs, controller) {
							console.log(scope.countObj);
						}
					}
				}
				// 这个link方法 与 compile 中的 post方法等价
//                    link:function postLink(scope, iElement, iAttrs, controller) {
////                        console.log(scope.countObj.count)
//                        console.log(iAttrs.countObj);
//                    }
			};
		});


angular.module("klwkOmsApp")
	.controller("AccordionDemoCtrl", ["$scope" ,function($scope) {
			$scope.count= 10;

			$scope.addCount = function(){
				$scope.count++;
			};
			$scope.minuseCount = function(){
				$scope.count--;
			};
}]);

原理说明:

1、使用scope 的“=” 属性,来实现controller中的scope与指令中的scope关联 

2、在指令的controller中使用 $watch方法来监听 $scope属性的变化,一旦变化,则调用指令内部的方法

猜你喜欢

转载自hbiao68.iteye.com/blog/2366533
今日推荐