0

我有一个在某些事件上动态变化的输入字段。

<input name="selectedId" id="selectedId" ng-model="selectedId" type="hidden" on-change="setUrl">

现在,我想在页面更改时将页面重定向到输入字段中存在的那个 id。

我的控制器

var app = angular.module("myApp", []).
  config(function($routeProvider, $locationProvider) {
    $routeProvider.
      when("/a1", { templateUrl: "partials/page1.html"}).
      when("/a2", { templateUrl: "partials/page2.html"}).
      otherwise( { redirectTo: "/a1" });
  });
app.controller("MainCtrl", function($scope, $location) {  
  $scope.setUrl=function($scope){
    if ($scope.selectedId) {
      alert($scope.selectedId);
    }
    else{
     alert("Out of scope"); 
    }
    //$location.path($scope.selectedId);
  };

在这里,我无法将输入字段值放入范围。我什至无法触发setUrl(),以便我可以重定向 URL。

我是 AngularJS 的新手,所以我需要了解这个概念。

4

2 回答 2

3
  1. 您正在使用on-change. AngularJS 有一个ngChange指令。用它。
  2. 一旦你使用 ngChange 也替换setUrlsetUrl().
  3. setUrl然后,从函数签名中删除 $scope 参数。$scope 在内部定义,MainCtrl因此它对其中定义的所有函数隐式可用。你不需要传递它。
  4. 您正在使用隐藏的输入从某个地方接收新的输入id,只是为了将其传递给setUrl功能。你不需要那个隐藏的输入。考虑使用 AngularJS 共享服务,或者事件广播,或者使用 $scope.$watch。
于 2013-06-18T10:05:00.250 回答
1

一种可能的解决方法是

在输入模型上注册一个手表并在该手表功能内更改位置

app.controller("MainCtrl", function($scope, $location) {  
 $scope.$watch('selectedId',function(newvalue,oldvalue){
  $location.path(newvalue);
 }
  };

<input name="selectedId" id="selectedId" ng-model="selectedId" type="hidden" >
于 2013-06-18T10:04:07.660 回答