我想获取在ng-click功能
中分配的变量值mainApp.controller('setSearchController',function($scope) {
$scope.getQuery = function(userq) //ng-click function
{
$scope.userq=userq;
};
alert($scope.userq); // showing Undefined even after the click is made
// Once clicked I want to use **userq** value to make one $https call
// apart from services,How to use userq here outside getQuery scope
});
在使用ng-click之前,可以获得未定义的值,但我想要做的是为另一个视图使用相同的控制器,这将在ng-click发生后呈现
.when('/search', {
templateUrl: "../static/views/seachResult.html",
controller: "setSearchController"
})
所以我想在$https
调用后在searchResult.html视图中获取一些搜索到的数据
答案 0 :(得分:0)
HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="getQuery('myVal')">Test</button>
<button ng-click="consoleIt(myVal)">Console</button>
</div>
控制器:
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.getQuery = function(a){
$scope[a] = a;
}
$scope.consoleIt = function(a){
console.log(a);
}
}]);
getQuery
函数会在作用域上创建一个新属性。属性的名称等于作为函数的agrument传递的(字符串)。 consoleIt
只是控制台记录它的agrument。在单击myVal
按钮之前,test
未定义。您也可以将变量(而不是字符串)传递给getQuery
,在这种情况下,只需从括号内删除引号。
答案 1 :(得分:0)
看看我的回答: Pass value in-between angular JS controller and services
同样的问题,我已经使用$ on和$ emit
解决了事件监听器的问题答案 2 :(得分:-1)
在语句函数getQuery中移动警报。
mainApp.controller('setSearchController', function($scope) {
$scope.userq = null;
$scope.getQuery = function(userq) //ng-click function
{
$scope.userq=userq;
alert($scope.userq);
};
});
或此解决方案
mainApp.controller('setSearchController', ['$scope', '$window', setSearchController]);
function setSearchController ($scope, $window) {
$scope.userq = null;
$scope.getQuery = function(userq) //ng-click function
{
$scope.userq=userq;
$window.alert($scope.userq);
};
}