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?
}
}