我有一个指令,它使用 ng-model 控制器并从它内部的控制器“myController”中获取模型值。我正在使用 transclude=true 和 ng-transclude。这是一个通用指令,我希望我的同事可以重复使用。我想让消费者单击按钮并将 ngModel 值设置为他们想要的任何值,但基本上总是一些对象。我该如何正确设置?我意识到在指令中我可以调用 ngModel.$setValue 或 $setViewValue 等......对不起,我对 angularjs 还是新手,特别是指令。我还应该在指令中使用控制器吗?我知道指令的对象定义具有这种能力,尽管我真的不知道如何或何时利用它。最后,可以将控制器转换为指令,如“nestedInDirController” ? 感谢您提供任何提示、技巧、示例或建议。
<div ng-controller="myController">
<div foo-directive="" ng-model="viewModel.foo">
<div ng-controller="nestedInDirController">
<various-controls-in-here />
</div>
</div>
</div>
angular.module('myApp', [])
.directive('fooDirective', function(){
var template = '<div><div ng-transclude></div> <button ng-click="someFunc()">I want to update ng-model in the directive, which in turn will update myController $scope.viewModel.foo</button></div>';
return {
transclude: true,
require: '?ngModel',
template: template,
compile: function(tElement, tAttrs, transclude){
return function(scope, element, attrs, ngModel){
}
}
};
});
function myController($scope){
$scope.viewModel = { foo : { bar: 'baz'}};
}
function nestedInDirController($scope){
$scope.someFunc = function(){
alert('I was called');
//how can I set ng-model in foo-directive from this controller?
}
}