1. 程式人生 > >AngularJS指令詳解(3)—指令與指令之間的互動

AngularJS指令詳解(3)—指令與指令之間的互動

上一節,我們瞭解了指令與控制器之間的互動,接下來看看指令與指令之間是如何進行互動的。

1.首先來了解一下什麼是獨立scope

為了更好的理解獨立scope,我們來看一段程式碼:

<div ng-controller="myController1">
       <hello></hello>
       <hello></hello>
 </div>

 var app=angular.module('firstApp',[]);//app模組名
    app.controller('myController1',['$scope'
,function($scope){ }]); app.directive('hello',function(){ return{ restrict:'E', template:"<div><input type='text' ng- model='username'/>{{username}}", replace:true } })

我們定義了一個指令,並在html中呼叫了兩次,我們發現,呼叫兩次的結果為:使用同一個指令構建的scope共享了一個數據,結果如下,我們在一個輸入框中輸入資料,會改變第二個指令中的輸入框
這裡寫圖片描述

如何解決這個問題呢,我們需要給指令生成獨立的scope,每次使用指令時,生成的scope都是獨立的,我們只需要如此修改:

app.directive('hello',function(){
        return{
            restrict:'E',
            scope:{},
            template:"<div><input type='text' ng-model='username'/>{{username}}",
            replace:true
        }
    })

結果如下:
這裡寫圖片描述

2.指令與指令之間的互動,指令的繼承

(1)首先我們定義了一個父指令,定義的方式如下:

app.directive('father',function(){
       return{
          restrict:'E',
          scope:{},
          controller:function($scope){
            this.mean1=function(){
              console.log('這是第一個方法....');
            };
            this.mean2=function(){
              console.log('這是第二個方法....');
            };
            this.mean3=function(){
              console.log('這是第三個方法....');
            }
          }
       }
    });

我們注意到,指令裡面也有controller,這裡的controller與控制器定義過程中的不同,這裡的controller指的是指令的獨立scope中定義的一些方法。

(2)定義子指令,子指令中可以使用父指令中scope中的方法:

app.directive('childFirst',function(){
        require:'^father',
        link:function(scope,ele,attr,fatherCtrl){
            fatherCtrl.mean1();
        }
 })

這樣通過:

require:'^father'

子指令就可以繼承並且使用父指令中,獨立scope中的一些方法。此時我

們的link函式就可以有第四個引數。

link和controller中方法的區別:

link中的方法是需要執行或者馬上要執行的方法。

controller中的方法是希望暴露出來,給外部使用的一些方法。

總結:指令之間的互動,是通過指令的controller中暴露出來的方法,給外部指令使用。