msforest / notebook

好记性不如烂笔头,记录知识的点点滴滴。
https://github.com/msforest/notebook/wiki
0 stars 0 forks source link

angularjs指令--隔离作用域 #2

Open msforest opened 7 years ago

msforest commented 7 years ago

指令的作用域介绍:通常,隔离指令的scope会带来很多的便利,尤其是你要操作多个scope模型的时候,但有时为了使代码能够正确工作,你也需要从指令内部访问scope的属性。 作用域表现形式有两种:

scope对象

当scope是一个对象的时候,指令的作用域与父极作用域就被隔开了。隔离作用域可能是最难理解的,但也是功能最强大的。具有隔离作用域的指令最主要的使用场景是创建可复用的组件,组件在未知的上下文中使用,并且可以避免污染所处的外部作用域或不经意地污染内部作用域。

接下来描述指令的绑定策略:

1.指令的本地属性(即模板里花括号中的属性)需要从本地取值,所以使用了controller选项,而在controller选项中,两个无参方法分别返回了父级scope中的title字符串和contents对象数组。

2.在HTML中,我们把设置了get-title和get-content的属性值为title和contents,这实际上就完成了与父级scope的绑定,因为我们才可以从那儿取得实质的内容。

带参数的方法

app.directive("direct",function(){ 
return{
            restrict: 'ECMA',
            template: '<div><input ng-model="model"/></div>\
<div><button ng-click="show({name:model})">show</button>',
            scope:{
                show:'&'              
            }                      
         }
    })
    .controller("nameController",function($scope){
        $scope.showName=function(name){ 
          alert(name); 
         } 
     });

指令使用:

<div ng-controller="nameController">
      <direct show="showName(name)"></direct> 
</div>

这个例子中,通过模板中的ng-click触发了show函数并将一个叫做model的对象作为name参数传递了进去,而在html中,我们把show的属性值设为showName(name)。