在角度js小例子中绑定丢失(点击后)

时间:2014-06-08 09:48:42

标签: ruby-on-rails angularjs

我在Angular JS中有一个非常小的应用程序。它被放置在更大的轨道应用程序中,但我没有看到太多的交互。角度应用程序允许用户与一组类别进行交互。很简单:

var angular_app = angular.module('angular_app', []);

angular_app.config(['$httpProvider', function($httpProvider, $cookieStore) {
//Protection
}]);

angular_app.controller('CategoriesController', function ($scope, $http) {

$scope.isEditing = false;
$scope.categoryName = '';

$http.get('/api/categories').success(function(data) {
    //We use this to data-bind with the HTML placed below
    $scope.categories = data;
});

$scope.addNewCategory = function() {
    ...
}

$scope.editCategory = function(index) {
    if (!index)
        return;

    var selectedCategory = $scope.categories[index];

    // With ng-show, we make visible the part of the UI 
    // that should be used for editing
    $scope.isEditing = true;
}

$scope.cancelEditCategory = function() {
    $scope.isEditing = false;
}

$scope.deleteCategory = function(index) {
    ...
}

});

angular.element(document).ready(function() {
    angular.bootstrap(document, ['angular_app']);
});

这个想法是信息显示在一个列表中,我们有一个'编辑'允许用户查看将允许他执行更改的UI的其他部分的按钮。

<div ng-controller="CategoriesController">
 <div ng-show='isEditing' class="popup_menu">
   DIV FOR EDITING
  </div>

  <ul>
     <li ng-repeat="category in categories">
        <a href="#" ng-click='deleteCategory($index)'>[X]</a>
        <a href="#" ng-click='editCategory($index)'>[E]</a>{{ category.name }}
      </li>
  </ul>

   <input type="text" id="categoryTextBox" ng-model="categoryName"/>
   <button id="submit" ng-click='addNewCategory()'>New category</button>

</div>

当我点击编辑按钮时,UI的相应部分变得可见,但就在此之后,某些事情发生了,应该呈现列表的ul完全失去了绑定,只显示如下内容:

 [X] [E]{{ category.name }}

必须显示时:

[X] [E]computer science
[X] [E]politics
[X] [E]news

(这是我在范围内的内容)。它在点击后发生几次(并且工作一秒)。 控制台没有错误,没有与其他库的交互(据我所见)。

谢谢!

2 个答案:

答案 0 :(得分:2)

<强> Turbolinks

我没有使用Angular的经验,但也许您的问题可能与Turbolinks有关 - 这是Rails仅加载页面的<body>标记的一种方式 - 保留<head>完好无损。

Turbolinks因为Rails上的Javascript而臭名昭着,因为每次重新加载<body>而不重新加载页面的<head>部分时,所有的JS绑定都将消失。在普通的JS中,解决方法是使用JQuery / Javascript delegation,并从document对象委派:

$(document).on("action", "delegated_object", function(){
 ...
});

道歉,如果这不起作用 - 这对我们来说是一个常见的问题,但由于我没有Angular的经验,我不知道它是否会对你有所帮助。

答案 1 :(得分:0)

似乎我应该对链接更加小心:

<a href="#" ng-click='deleteCategory($index)'>[X]</a>
<a href="#" ng-click='editCategory($index)'>[E]</a>{{ category.name }}

不确切知道这是如何工作的,但似乎如果链接具有他的href属性,则针对127.0.0.1发出GET请求,以某种方式破坏角度代码。如果你把它们像:

<a ng-click='deleteCategory($index)'>[X]</a>
<a ng-click='editCategory($index)'>[E]</a>{{ category.name }}

问题将得到解决。感谢大家的阅读和帮助!