我试图从Angular控制器中获取HTML元素的值。
<div ng-app="myApp" ng-controller="myControler">
<br />
<input id="Text1" type="text" runat="server" value="aValue" /
我的控制器:
var myApp = angular.module('myApp', []);
myApp.controller("myControler", function ($scope, $document) {
var name = angular.element($('#Text1')).val();
console.log(name);
});
但名称返回&#34;未定义&#34; ...
请问,我做错了什么?
答案 0 :(得分:14)
angular.element
是jquery $
的别名。
您可以像这样访问该元素:angular.element('#Text1').val();
ng-model
是实现这一目标的有条理的方式。您可以使用ng-init
<input id="Text1" type="text" runat="server" ng-model="inputVal" ng-init="inputVal='aVal'">
可以使用范围console.log($scope.inputVal);
JSfiddle示例:http://jsfiddle.net/n1oppeu2/
答案 1 :(得分:6)
为什么你需要使用angular元素来访问表单元素?
您可以通过将模型绑定到它来获取和设置值
像这样import numpy as np
import pulp
from itertools import product
threshold = 200
model = pulp.LpProblem('selection', pulp.LpMaximize)
similarity = np.array([[1., 0.08333333, 0.1, 0., 0., 0.0625],
[0.08333333, 1., 0.33333333,
0., 0.11111111, 0.07692308],
[0.1, 0.33333333, 1., 0.2, 0., 0.09090909],
[0., 0., 0.2, 1., 0., 0.],
[0., 0.11111111, 0., 0., 1., 0.27272727],
[0.0625, 0.07692308, 0.09090909, 0., 0.27272727, 1.]])
ingredients = ['var_%d' % i for i in range(6)]
ingredient_pairs = ['var_{}_{}'.format(
ingredients.index(var[0]), ingredients.index(var[1]))
for var in product(ingredients, ingredients)
if ingredients.index(var[0]) > ingredients.index(var[1])]
# Flatten the similarity array
indices = np.triu_indices_from(similarity)
similarity = similarity[indices]
scores = np.random.randint(1, 3, size=len(ingredients))
costs = np.random.randint(20, 60, len(ingredients))
scores = dict(zip(ingredients, scores))
costs = dict(zip(ingredients, costs))
similarity = dict(zip(ingredient_pairs, similarity))
x = pulp.LpVariable.dict(
'x_%s', ingredients, lowBound=0, upBound=1, cat=pulp.LpInteger)
y = pulp.LpVariable.dict(
'y_%s', ingredient_pairs, lowBound=0, upBound=1, cat=pulp.LpInteger)
model += sum([scores[i] * x[i] for i in ingredients]) + sum([
similarity[i] * y[i] for i in ingredient_pairs])
model += sum([costs[i] * x[i] for i in ingredients]) <= threshold
for pair in ingredient_pairs:
indexes = pair.split('_')[1:]
for index in indexes:
# y_{ij} <= x_i and y_{ij} <= x_j Q
model += y[pair] <= x['var_{}'.format(index)]
# y_{ij} >= x_i + x_j - 1
model += y[pair] >= sum(x['var_{}'.format(i)] for i in indexes) - 1
solver = pulp.solvers.PULP_CBC_CMD()
model.solve(solver)
model.writeLP('similarity.lp')
print 'Objective: {}'.format(pulp.value(model.objective))
for v in model.variables():
if v.varValue > 10e-4:
print v.name, v.varValue
控制器
<input id="Text1" type="text" runat="server" ng-model="input.field1" />
答案 2 :(得分:1)
使用角度元素选择器#
<input id="Text1" type="text" runat="server" value="aValue" />
console.log(angular.element('#Text1').val());
或
console.log(angular.element('#Text1')[0].value);