ボタンがクリックされたときに両方 の
関数を実行 し
たい
<button href="#" ng-click="showPost();showComment()" class="btn">show</button>
ネストされたコントローラーの概念を指定せずにそれを行うにはどうすればよいですか
ボタンがクリックされたときに両方 の
関数を実行 し
たい
<button href="#" ng-click="showPost();showComment()" class="btn">show</button>
ネストされたコントローラーの概念を指定せずにそれを行うにはどうすればよいですか
これは、service/factory を使用して実現できます。これがどのように機能するかの簡単な例を次に示します。
JS
var myApp = angular.module('myApp', []);
function CommentController($scope, myStorage) {
$scope.myStorage = myStorage;
$scope.showMe = function(){
myStorage.setIndex(3);
}
}
function PostController($scope, myStorage) {
$scope.myStorage = myStorage;
}
myApp.factory('myStorage', function () {
var currentBusinessIndex = 0;
return {
getIndex: function () {
return currentBusinessIndex;
},
setIndex: function (index) {
currentBusinessIndex = index;
}
}
});
HTML
<div ng-controller="CommentController">
<button ng-click="showMe();">press me</button>
<pre>{{myStorage.getIndex()}}</pre>
</div>
<div ng-controller="PostController">
<pre>{{myStorage.getIndex()}}</pre>
</div>
デモFiddle
さらに、 を使用してサービス データを監視し、$watch
データの変更をトリガーすることができます。