directive指令間的交互
directive指令依賴
- require:'^girl'自己身上找找不到向上找,找到則會在link函數的第四個參數增加girl控制器的實例
- require:'^?girl'如果沒有依賴到使用的是? 則得到的值是null绘盟,否則報錯
app.directive('loveMoney',function () {
return {
require:'^?girl',
link: function (scope,element,attrs,girlCtrl) {
girlCtrl.add('loveMoney');
}
}
});
opener組demo
樣式:
.title{
width: 100px;
height: 30px;
line-height: 30px;
background: yellow;
}
.content{
width: 100px;
height: 100px;
background: red;
}
增加指令組:
<group>
<opener title="標題1">這是內容1</opener>
<opener title="標題2">這是內容2</opener>
</group>
增加引用模板:
<div class="title" ng-click="show()">{{title}}</div>
<div class="content" ng-show="flag" ng-transclude></div>
增加指令
app.directive('group', function () {
return {
controller: function ($scope) {
var arr = [];
this.add = function (scope) {
arr.push(scope);
}
this.close = function (scope) {
for(var i = 0; i<arr.length;i++){
if(arr[i]!=scope){
arr[i].flag = false;
}
}
}
}
}
});
app.directive('opener',function () {
return {
templateUrl:'open.html',
transclude:true,
require:'^group',
scope:{
title:'@'
},
link:function(scope,element,attrs,groupCtrl){
scope.flag = false;
scope.show = function () {
scope.flag = !scope.flag;
groupCtrl.close(scope);
};
groupCtrl.add(scope);
}
}
});
angular方法
$watch(watchExpression, listener, objectEquality)
監(jiān)聽模型變化
$scope.$watch(function() {
return $scope.foo;
}, function(newVal, oldVal) {
console.log(newVal, oldVal);
});
watchExpression:監(jiān)聽的對象晤碘,它可以是一個angular表達式如'name',或函數如function(){return $scope.name}斑匪。
listener:當watchExpression變化時會被調用的函數或者表達式,它接收3個參數:newValue(新值), oldValue(舊值), scope(作用域的引用)
objectEquality:是否深度監(jiān)聽喊递,如果設置為true,它告訴Angular檢查所監(jiān)控的對象中每一個屬性的變化. 如果你希望監(jiān)控數組的個別元素或者對象的屬性而不是一個普通的值, 那么你應該使用它
$apply
AngularJS外部的控制器(DOM 事件袭艺、外部的回調函數如 jQuery UI 空間等)調用了AngularJS 函數之后庸诱,必須調用$apply敛助。即不是angular自帶的方法粗卜,數據更新不會影響視圖在這種情況下,你需要命令 AngularJS刷新自已纳击。
$http
我們可以使用內置的$http服務直接同外部進行通信续扔。$http服務只是簡單的封裝了瀏覽器原生的XMLHttpRequest對象,用法同jquery
$http服務是只能接受一個參數的函數,這個參數是一個對象焕数,包含了用來生成HTTP請求的
配置內容纱昧。這個函數返回一個promise對象,具有success和error兩個方法堡赔。返回一個promise對象
var promise=$http({
method:'GET',
url:"data.json"
});
由于$http方法返回一個promise對象识脆,對象中有一個then方法來處理回調,方法中有兩個參數善已,第一個是成功的回調第二個是失敗的回調
$http.jsonp(
$sce.trustAsResourceUrl(
'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+$scope.query),
{jsonpCallbackParam: 'cb'})
.then(
function (res) { //成功
$scope.arrs = res.data.s;
},
function (err) { //失敗
console.log(err);
});