angular js中指令directive有个特别实用的东西,那就是 isolate scope (被隔离的scope)
关于详细他和全局的scope 有什么差别。能够參考以下这篇博文:
AngularJS 全局scope与Isolate scope通信
本文主要解说 其详细的几种使用方式:
1. = 的使用
[html]
<div class="card" ng-repeat="app in apps">
<app-info info="app"></app-info>
</div>
[js]
app.directive('appInfo', function() {
return {
restrict: 'E',
scope: {
info: '=' //假设是 = 就是info属性的值 赋给 当前scope.info
},
templateUrl: 'js/directives/appInfo.html'
};
});
2. =属性名 的使用
[html]
<div ng-controller="AppCtrl as appctrl">
Ctrl
<input type="text" ng-model="appctrl.ctrlFlavor"> Dir
<div ab="25" drink="123456" flavor="appctrl.ctrlFlavor"></div>
</div> [js]
var app = angular.module("drinkApp", []); app.controller("AppCtrl", function() {
var appctrl = this;
appctrl.ctrlFlavor = "blackberry";
}); app.directive("drink", function() {
return {
scope: {
flavor: "=ab"
},
template: '<input type="text" ng-model="flavor">'
};
});
显示结果:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
3. @ = 和 & 的综合使用
html 代码:
<div class="mainController" ng-app="isolateApp">
<div ng-controller="AppCtrl">
<div class="row">
<character
name="Roman Regins"
image="img/p1.jpg"
movetype="movetype"
use-move="getMove(name,movetype,move)"
class="col-xs-4"></character>
<character
name="Seth Rollins"
image="./img/p2.jpg"
movetype="movetype"
use-move="getMove(name,movetype,move)"
class="col-xs-4"></character>
<character
name="Dean Ambrose"
image="./img/p3.jpg"
movetype="movetype"
use-move="getMove(name,movetype,move)"
class="col-xs-4"></character>
</div>
</div>
</div>
js控制:
//显示@ = 和 &综合的
var app = angular.module('isolateApp',[]);
app.controller("AppCtrl",['$scope',"$element",function($scope,$element){
$scope.getMove = function(name,movetype,move){
console.log(name+'$$$'+movetype+'$$$'+move);
}
$scope.movetypes = ['amove','bavi','cmp4'];
$scope.movetype = $scope.movetypes[0];
}])
.directive("character",function(){
return {
restrict:"E",
scope:{
name:"@", //@指的是属性的值赋给name 仅此而已
image:"@",
movetype:"=", //表示类型等于当前属性的值
useMove:"&" //&表示相应的函数的引用 及该属性相应的函数别名就是他了
},
controller:"AppCtrl", //仅仅有这里声明了 才会将select选项加载进来
replace:true,
templateUrl:"shield_isolate.html"
};
})
模板:
<script type="text/ng-template" id="shield_isolate.html">
<div class="panel panel-default">
<div class="panel-body">
<div>
<figure>
<img src="{{image}}">
<figcaption>{{name}}</figcaption>
</figure>
</div>
</div>
<div>Move:
<input type="text" ng-model="value" class="form-controller"/>
</div>
<div>
Select Move Type:
<select ng-model="movetype"
ng-options="movetype for movetype in movetypes">
</select>
</div>
<div class="panel-footer clearfix">
<div class="btn btn-primary"
ng-click="useMove({name:name,movetype:movetype,move:value})"
>Action!</div>
//这里的":"前的三个參数分别相应 父函数的三个參数的名称
//":" 后的三个參数则相应 给定值scope 的三个属性 以便一一相应传值
</div>
</div>
</script>
显示结果:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">