2014-10-17 20 views
0

我有这个网站PARAMATERS变得不确定

<div ng-controller = "RetrieveCtrl as retrieve" > 
    <form> 
     <input ng-model = "retrieve.input1"> 
     <input ng-model = "retrieve.input2"> 

     <button type="submit" ng-click="retrieve.retrieveEntry()">Search</button> 
. 
. 
. 

与此控制器

app.controller('RetrieveCtrl', ['$scope' , '$http', function($scope, $http) { 

    $scope.retrieveEntry = function() { 

     var input1 = $scope.retrieve.input1; 
     var input2 = $scope.retrieve.input2; 

     // validate input1 & input2 first... 
     // input1 & input2 part of URL 

     $http.get(... 


     ) 

    }; 

} 

这是工作的罚款,我能够从Web服务检索我的数据。我想要做的就是要重构功能分为两个:

app.controller('RetrieveCtrl', ['$scope' , '$http', function($scope, $http) { 

    $scope.clickSearch = function() { 

     var input1 = $scope.retrieve.input1; 
     var input2 = $scope.retrieve.input2; 

     // validate input1 & input2 first... 
     $scope.retrieveEntry(input1, input2); 

    }; 

    $scope.retrieveEntry = function (a, b) { 


     // build a and b in URL 
     $http.get(... 


     ) 

    }; 

} 

,这样我可以在其他功能重用$scope.retrieveEntry。但是,在将功能分成两个(按钮的ng-click更新为"retrieve.clickSearch()")之后,a和b变得未定义。我怀疑它与$scope有关,对此我没有太清楚的理解(我仍然对此非常困惑,$scope)有人可以解释背后发生了什么以及如何解决这个问题吗?

谢谢。

回答

1

我不确定这是否会解决您的问题,但是您没有正确使用控制器作为语法。您控制器实现应该是这个样子:

app.controller('RetrieveCtrl', ['$scope' , '$http', function($scope, $http) { 
    var self=this; 
    self.clickSearch = function() { 
     // validate input1 & input2 first... 
     self.retrieveEntry(self.input1, self.input2); 

    }; 

    self.retrieveEntry = function (a, b) { 


     // build a and b in URL 
     $http.get(... 


     ) 

    }; 

} 

一旦你开始使用控制器作为语法,主要是为了你的控制器不直接范围添加功能。

+0

我实际上更喜欢使用'this'(或self),因为我在较新的代码示例中看到了这一点,它对我而言经常适用。然而,我不得不使用'$ scope'(我在angularjs的旧例子中看到这个),为了与我的同事的代码保持一致,大多数使用'$ scope'。我不能证明现在使用'this',因为我自己对'this'和'$ scope'还不是很清楚(并且不能很好地解释它们),而且,我们已经有一个代码库可以工作上。 – menorah84 2014-10-17 07:22:22

+0

您显示的代码直接将函数添加到作用域,而视图中的函数使用'retrieve'引用。这是一个错字。 – Chandermani 2014-10-17 07:45:55

+0

这不是一个错字错误,它的工作(我的同事这样做)。这是句法糖(我称之为别名),对吧?将函数直接附加到'$ scope'是否是不正确/错误的做法?根据我的理解,“这个”和“范围”可能不一样,但我的理解仍然混乱。使用'this'或'self'总是适合我,而你的解决方案确实有效。 – menorah84 2014-10-17 07:56:40