0

這是我正在使用的代碼(並且已經在整個項目中使用過),範圍已更新,但是ng-repeat不會刷新,我正在使用scope。$ apply。 。不知道爲什麼,幾個開發也採取了看看代碼..無解..

指令:

app.directive("addBrandSettings", function(){ 
    return { 
     restrict: "A", 
     link: function(scope, element, attrs){ 
      element.bind("keypress", function(e){ 
       if(e.which === 13){ 
        var brand = element.val(); 
        scope.$apply(function(){ 
         scope.settings.brands.push(brand); 
         console.log(scope.settings.brands); 
        }) 
        element.val(""); 
       } 
      }) 
     } 
    } 
}); 

HTML:

<input add-brand-settings type="text" placeholder="Add Brand"/> 
<p ng-repeat="brand in settings.brands">{{brand}}<a remove-brand-settings index="{{$index}}" href="#"><i class="fa fa-times-circle"></i></a></p> 

範圍:

$scope.settings = { 
     companyInfo: { 
      name: "", 
      email: "", 
      phone: "", 
      website: "" 
     }, 
     users: [ 
      { 
       username: "Supreme Manager", 
       role: "Super User", 
       password: "asdasd" 
      }, 
      { 
       username: "Regular Grunt", 
       role: "User", 
       password: "asdasd" 
      } 
     ], 
     brands: [ 
      "Maxi", 
      "Chipsy", 
      "Bananice" 
     ], 
     retailers: [ 
      "Maxi", 
      "Ikea", 
      "Tempo" 
     ] 
    } 
+0

做一個小提琴,但我目前的猜測是,你有一個孤立的範圍,沒有得到更新。 – Dieterg

回答

1

您的代碼完美的作品,所以你可能有一些語法問題什麼的,這裏有一個工作示例:

var app=angular.module('App', []); 
function ctrl($scope){ 
    $scope.settings = { 
     companyInfo: { 
      name: "", 
      email: "", 
      phone: "", 
      website: "" 
     }, 
     users: [ 
      { 
       username: "Supreme Manager", 
       role: "Super User", 
       password: "asdasd" 
      }, 
      { 
       username: "Regular Grunt", 
       role: "User", 
       password: "asdasd" 
      } 
     ], 
     brands: [ 
      "Maxi", 
      "Chipsy", 
      "Bananice" 
     ], 
     retailers: [ 
      "Maxi", 
      "Ikea", 
      "Tempo" 
     ] 
    } 
} 
app.directive("addBrandSettings", function(){ 
    return { 
     restrict: "A", 
     link: function(scope, element, attrs){ 
      element.bind("keypress", function(e){ 
       if(e.which === 13){ 
        var brand = element.val(); 
        scope.$apply(function(){ 
         scope.settings.brands.push(brand); 
         console.log(scope.settings.brands); 
        }) 
        element.val(""); 
       } 
      }) 
     } 
    } 
}); 

HTML:

<div ng-app="App" ng-controller="ctrl"> 
<input add-brand-settings type="text" placeholder="Add Brand"/> 
<p ng-repeat="brand in settings.brands">{{brand}}<a remove-brand-settings index="{{$index}}" href="#"><i class="fa fa-times-circle"></i></a></p> 
</div> 

活生生的例子:http://jsfiddle.net/choroshin/7zVd2/

+0

thx兄弟,至少我知道現在不去尋找的地方 – Arcagully