我需要在指令(num1,num2)之外获取输入值,以便在点击按钮时计算结果(添加)。这样做的正确方法是什么? 这是我的HTML
<div ng-app="sumApp" >
<div ng-controller='sumAppCtrl' >
<input ng-model='num1' type='text' >
<span>+</span>
<input ng-model='num2' type='text'>
<span>=</span>
<bp-sum></bp-sum>
<input type="button" value="Sum" ng-click="sumNumbers(num1,num2)" />
</div>
</div>
和js代码:
var sumApp = angular.module('sumApp', []);
sumApp.controller("sumAppCtrl", function ($scope) {
});
sumApp.directive('bpSum',function( ){
return {
restrict:'E',
controller:
sumNumbers = function(num1,num2){
var items=[parseInt(num1),parseInt(num2)];
$scope.addition = _.reduce(items, function(memo, num){ return memo + num; }, 0);
},
template:"<input type='text' ng-model='addition' />"
}
})
答案 0 :(得分:0)
据我说..你应该像这样开发添加组件
<div ng-app="sumApp" >
<div ng-controller='sumAppCtrl' >
<bp-sum></bp-sum>
</div>
</div>
<强>指令强>
sumApp.directive('bpSum', function() {
return {
restrict: 'E',
controller: function($scope) {
$scope.sumNumbers = function(num1, num2) {
var items = [parseInt(num1), parseInt(num2)];
$scope.addition = _.reduce(items, function(memo, num) {
return memo + num;
}, 0);
};
},
template: " <input name='num1' ng-model='num1' type='text' >" +
"<span>+</span>" +
"<input name='num2' ng-model='num2' type='text'>" +
"<span>=</span><input type='button' value='Sum' ng-click='sumNumbers(num1,num2)'' />"+
"<label>Sum is : </label> <input type='text' ng-model='addition' />"
};
});