[英]Passing data from custom directive into parent controller
我創建了自定義的角度指令。 例如:
自定義指令:
var app=angular.module('app',[]);
app.directive('customDirective',function(){
return{
restrict:A,
controller:customDirectiveController,
scope:{
someArray:"="
}
}
})
自定義指令控制器:
app.controller('customDirectiveController',function(scope){
scope.someArray=[];
scope.someArray.push(1);
scope.someArray.push(2);
scope.someArray.push(3);
});
父控制器:
app.controller('parentCtrl',function($scope){
$scope.result=[];
});
HTML:
<div data-ng-controller="parentCtrl">
<div data-custom-directive="result">
</div>
如何從自定義指令獲取此someArray的值到父控制器(父控制器中的結果變量應與自自定義指令控制器的someArray相同)?
這是jsfiddle http://jsfiddle.net/mehmedju/RmDuw/302/謝謝
假設您使用的是tempController,那么您的代碼應該是
app.controller('tempController', function($scope) {
scope.someArray = []
});
的HTML代碼是
<div ng-controller="tempController">
<div custom-directive some-array="someArray">
</div>
您可以在數組上應用“ $ watch” ,如下所示:
在控制器中:
app.controller('MainCtrl', function($scope) {
$scope.someArray = [];
})
在HTML中:
<div custom-directive arr="someArray">
</div>
在指令中:
app.directive('customDirective', function(){
return {
scope: {
arr: '='
}
}
link: function(scope, element, attrs) {
scope.$watch('arr', function(newVal, oldVal) {
//do your array manipulation here
}
}
})
在控制器中 ,創建一個函數,該函數將接受從指令返回的值,例如:
app.controller('MainCtrl', function(){
$scope.watchVal = function(val) {
//do array manipulation
$scope.apply(); //to update the scope
}
})
在HTML中:
<div custom-directive data-method="watchVal">
</div>
在指令中:
app.directive('customDirective', function(){
return {
scope: {
sendVal: '&method'
},
link: function(scope, element, attrs){
scope.updateVal = function(){
var func = scope.sendVal();
func(scope.someArray);
}
}
}
})
您在此處有一篇關於觀察者的非常有趣的文章,網址為http://teropa.info/blog/2014/01/26/the-three-watch-depths-of-angularjs.html
您需要使用watchCollection
而且,如果您正在創建數組並更改指令內的引用,則可能會丟失觀察程序內的引用。 這意味着不要創建或更改內部的數組引用。
另一個有趣的方法是使用ngModel http://jsfiddle.net/ta66J/
var app = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.formVals = {
dirVals: [
{val: 'one'},
{val: 'two'}
]
};
}
app.directive('dir', function($compile) {
return {
restrict: 'E',
compile: function(element, attrs) {
var html = "<input id='inputId' type='text' ng-model='" + attrs.dirModel + "' />";
element.replaceWith(html);
return function(scope, element, attrs, ngModel) {
$compile(angular.element(element))(scope);
};
},
};
});
jsfidler來自以下有趣的線程: https ://groups.google.com/forum/#!topic/angular/QgcRBpjiHAQ
這是已解決的問題。
<div custom-directive="" data-some-array="result"></div> {{result}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.