简介
上一节讲了自定义指令的配置项,这一节我们看下自定义指令的作用域,自定义指令在开发中对于功能的抽取有着至关重要的作用,努力加油吧!😄💪
例子
<div ng-app="myController">
<h1>父级消息:{{msg}}</h1>
<input type="text" ng-model="count" />
<my-directive parent-msg="Angular" myname="AngularJs" pmsg2="{{msg}}" pmsg3="count" p-fun="fun(msg)"></my-directive>
</div>
<script>
var app = angular.module("myController", []);
app.controller("myController",["$scope",function($scope){
//angular会默认创建一个指令作用域并原型式继承父级作用域
$scope.pmsg = "父消息";
$scope.count = 0;
$scope.fun = function(val) {
console.log(val+"被触发");
}
}]);
app.directive("myDirective",function() {
return {
//scope:false,
scope: {
parentMsg: "@",
myname:"@",
name:"@myname",//myname第二种写法
pmsg2:"@",//拿到父级作用域的值
pmsg3:"=",//双向数据绑定
pFun: "&"
},
template:`
<div>
<h1>自定义指令</h1>
<h2>继承于父级作用域:{{pmsg}}</h2>
<input type="text" ng-model="msg" />
<h1>{{parentMsg}}</h1>
<h1>{{myname}}</h1>
<h1>{{name}}</h1>
<h1>{{pmsg2}}</h1>
<h1>{{pmsg3}}</h1>
<input type="text" ng-model="pmsg3" >
<button ng-click="pFun({msg:parentMsg})">点击</button>
</div>
`
}
})
</script>
scope: 如果scope指定为false,指令会继承自己的父级作用域。(非常不严谨,不建议使用),当scope指定为true时,指令会创建自己的作用域,并继承父级作用域。
scope:{}当scope为对象时,表明创建的是隔离作用域,这时候此作用域与其他作用域不产生依赖或影响(非常强大)
父子传值:@
不积跬步无以至千里,不积小流无以成江海