我想在表单提交上运行一些jQuery代码。我希望它可以重复使用,并且我已经设置了一个工厂,用于在控制器之间交换数据。
HTML (jsfiddle)
<div ng-app="myApp">
<div id="div_1" ng-controller="FirstCtrl">
<form ng-submit="Data.submit('#div_1','#div_2')">
<input type="text" ng-model="Data.FirstName"><br>
Input is : <strong>{{Data.FirstName}}</strong>
<input type="submit" value="Submit" />
</form>
</div>
<div id="div_2" style="display:none;" ng-controller="SecondCtrl">
Second controller to verify data is being shared: <br>
<strong>{{Data.FirstName}}</strong>
</div>
</div>
的Javascript
var myApp = angular.module('myApp', []);
myApp.factory('Data', function(){
var root = {
FirstName: ''
};
root.submit = function(to_hide, to_show) {
$(to_hide).slideUp(function(){
$(to_show).slideDown();
});
}
return root;
});
myApp.controller('FirstCtrl', function( $scope, Data ){
$scope.Data = Data;
});
myApp.controller('SecondCtrl', function( $scope, Data ){
$scope.Data = Data;
});
这有效,但我觉得我正在攻击它。有没有更好的方法呢?
更重要的是,这样做的 Angular Way 是什么?
顺便说一句,由于纯CSS动画,我没有使用ngAnimate。我仍然希望旧浏览器能够体验这些动画。
答案 0 :(得分:1)
DOM操作调用可能应该封装在一个指令中。传递要操纵的元素,并将Data
对象传递给指令。
指令:
myApp.directive('hideShow', function () {
return {
restrict: 'A',
scope: {
hideSelector: '=',
showSelector: '=',
data: '=hideShow'
},
link: function(scope, element, attrs) {
element.submit(function (e) {
e.preventDefault();
alert(scope.data.FirstName);
$(scope.hideSelector).slideUp(function(){
$(scope.showSelector).slideDown();
});
});
}
};
});
HTML
<div id="div_1" ng-controller="FirstCtrl">
<form hide-show="Data" hide-selector="'#div_1'" show-selector="'#div_2'">
<input type="text" ng-model="Data.FirstName"><br>
Input is : <strong>{{Data.FirstName}}</strong>
<input type="submit" value="Submit" />
</form>
</div>