我有一個使用ng模型控制器的指令,並從它內部的控制器「myController」獲取模型值。我正在使用transclude = true和ng-transclude。這是我希望允許我的同事重複使用的通用指令。我想讓消費者點擊按鈕,並將ngModel值設置爲他們想要的任何值,但基本上總是有一些對象。我如何正確設置?我意識到裏面的指令,我可以調用ngModel。$ setValue或$ setViewValue等...抱歉,我仍然是新的angularjs,特別是指令。我應該在指令中使用控制器嗎?我知道指令的對象定義具有這種能力,但我並不真正知道如何或何時利用它。最後可以將控制器轉換爲指令,就像在「nestedInDirController」中一樣?感謝您提供任何提示,技巧,示例或建議。在Angularjs中,嵌套在指令中的控制器可以設置指令的ng模型嗎?
<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?
}
}
'nestedInDirController'已經訪問了在'myController'的範圍定義的屬性,因爲範圍prototypically繼承。在你的'nestedInDirController'裏面,這是有效的:'console.log($ scope.viewModel)'這樣做:'$ scope.viewModel.foo.bar =「testing」;' –