[英]How to retrieve values from a custom directive and pass them to a controller
我的主要html文件结构如下:
<html ng-app='information'>
<body ng-controller="FirstController as first>
<div ng-controller="SecondController as second>
以下是自定义指令。
<!-- Custom Directive -->
<div id="information">
<myOwnDirective ng-controller="ThirdController as thirdCtrl"></myOwnDirective>
</div>
指令创建如下:
(function() {
var app = angular.module('information', ['ui.bootstrap']);
app.directive('myOwnDirective', function(){
return {
restrict: 'E',
templateUrl: 'my-own-directive.html',
};
});
这是我的自定义指令模板:
<uib-accordion tag ng-repeat="info in first">
<form ng-submit="thirdCtrl.updateInformation()">
<div class="form-group">
<label for="someprop">Property</label> <input type="text" name="someprop"
class="form-control" ng-model="info.propValue"
ng-readonly="info.propValue">
</div>
<button type="submit" class="btn btn-success btn-lg btn-block">Click</button>
</form>
这是我的控制器,这里有要在自定义指令模板中的ng-click上调用的函数。
(function() {
angular.module('deviceInfo2').controller('FormController', [ '$scope','$http', function($scope) {
this.updateStatus =function () {
console.log("Inside function");
};
}]);
})();
我想在ng-click上的自定义指令模板中获取数据,并将其传递给表单控制器,但是我似乎无法找到在其中获取数据的方法。 我尝试探索创建服务,但无法正常工作。 我想我错过了范围。 谁能指出我正确的方向。 我已经坚持了一段时间,需要取得一些进展。 谢谢。
如果您发现自己创建了一个可生成整个Web表单的指令,则应质疑您的方法。 想小一点。 太多的指令不是很可重用,并且您经常会遇到这种情况。
除了创建可生成整个Web表单的指令之外,为什么不仅将Web表单创建为视图模板? 为什么还要有自定义指令?
如果您的答案是:“我希望此Web表单出现在我的应用程序中的多个位置”,请考虑使用ng-include或ui-router创建可重用状态。 指令是自定义HTML元素(或属性),而不是用于处理大量代码的橡皮图章。
如果仍然需要自定义指令将数据提供给父指令,那么一种好方法是使用&
数据绑定。
工作示例: JSFiddle
angular.module('myApp', [])
.controller('MyController', MyController)
.controller('MySelectController', MySelectController)
.directive('mySelect', mySelectDirective)
;
function MyController() {
var vm = this;
vm.setValue = function(value) {
vm.value = value;
};
}
function MySelectController() {
var vm = this;
vm.items = [
{label: 'One', value: 1},
{label: 'Two', value: 2},
{label: 'Three', value: 3}
];
}
function mySelectDirective() {
return {
bindToController: {
callback: '&'
},
controller: 'MySelectController',
controllerAs: 'vm',
link: postLink,
scope: true,
template: '<select ng-model="vm.selected" ng-options="item.value as item.label for item in vm.items"></select>'
};
function postLink(scope, iElement, iAttrs, vm) {
scope.$watch(function() {
return vm.selected;
}, function(newValue) {
if (angular.isDefined(newValue) && typeof vm.callback === 'function') {
vm.callback({$value: newValue});
}
});
}
}
<div ng-controller="MyController as vm">
<my-select callback="vm.setValue($value)"></my-select>
<p>Selected Value: {{vm.value}}</p>
</div>
如果您的控制器范围中有一个范围变量,请说
$scope.var1 = '';
确保控制器的局部位于使用自定义指令的位置。 然后,在指令的控制器中,可以在下面使用此命令将值推入控制器的作用域:
$scope.$parent.var1 = 'value to pass';
这里的假设是您的指令具有隔离范围。 控制器的作用域是指令作用域的父级,因此可以使用$parent
关键字传递数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.