在AngularJS中,我们通常会使用自定义指令,最常用的方式就是将自定义指令中的属性和controller中的字符、变量、函数绑定起来,用于实现模块化,方便视图层和业务层的分离,举例如下:
我们想通过属性的方式去给自定义指令填充一个字符串:
<html lang="en" ng-app="myApp1"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body ng-controller="testController3"> <hd uname="{{userName}}" ></hd> </body>
如果没有绑定策略,我们只能这样去写:
var myApp1=angular.module("myApp1",[]); myApp1.controller("testController3",function($scope){ $scope.userName="你好,优百"; }) //自定义指令 myApp1.directive("hd",function(){ return{ scope:{ }, restrict : 'AE', template : '<div ng-bind="uname"></div>', replace : true, link:function(scope,element,attrs){ //获取指令属性uname的userName,然后填充到指令的div中 scope.uname=attrs.uname; } } })
这个是比较麻烦的,ng给我提供了三种绑定策略:分别为@、=、&
一、“@”是绑定字符串,用于自定义指令绑定controller中的变量的字符串,比如实现上面代码相同的功能,我们就可以这样定义:
var myApp1=angular.module("myApp1",[]); myApp1.controller("testController3",function($scope){ $scope.userName="你好,优百"; }) //指令 myApp1.directive("hd",function(){ return{ scope:{ //定义@连接符绑定到uname上面 uname:'@' }, restrict : 'AE', template : '<div ng-bind="uname"></div>', replace : true, //link:function(scope,element,attrs){ //获取指令属性uname的userName,然后填充到指令的div中 // scope.uname=attrs.uname; //} } })
二、“=”是绑定变量,用于自定义指令绑定controller中的变量:
如:
html { <html lang="en" ng-app="myApp1"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body ng-controller="testController4"> <input type="text" ng-model="userName"> <hdd uname="userName" ></hdd> </body> }
ng代码
var myApp1=angular.module("myApp1",[]); myApp1.controller("testController4",['$scope',function($scope){ $scope.userName="你好优百"; }]) //指令 myApp1.directive("hdd",function(){ return{ restrict : 'AE', scope:{ uname : '=' }, template : '<input type="text" ng-model="uname">' } })
上面的代码可以实现自定义指令中的uname可以和controller中的$scope.userName实现双向数据绑定;
三、“&”是绑定函数,用于自定义指令绑定controller中的函数:
html
<html lang="en" ng-app="myApp1"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body ng-controller="testController4"> <hdd uname="usd(name)" ></hdd> </body>
ng代码
var myApp1=angular.module("myApp1",[]); myApp1.controller("testController4",['$scope',function($scope){ $scope.usd=function(name){ alert("hi"+name); }; }]) //指令 myApp1.directive("hdd",function(){ return{ restrict : 'AE', scope:{ uname : '&' }, template : '<input type="text" ng-model="userName"> <button ng-click="uname({name:userName})">点击</button>' } })
上面的代码可以在自定义指令中通过ng-click=”uname({name:userName})” 绑定到controller中的$scope.usd方法,实现函数之间的双向绑定。
共有 0 条评论