Anjular JS和指令,ng-repeat和模板绑定

时间:2015-10-20 00:52:00

标签: javascript angularjs

我是anjular的新手,请原谅我,如果我的一些术语错了。

我在下面创建了一个简化示例,我试图在指令中获取模板以绑定ng-repeat。如果您更新输入,则简单{{list.name}}会更新,但{{formattedtext}}不会更改。

如何获取格式化文本以反映正确的值?

HTML

<div ng-repeat="list in List" style="border: 1px solid;">
    <list-item>
    </list-item>
</div>
<div ng-repeat="list in List" style="border: 1px solid;">
    <input ng-model="list.name" />
</div>

app.js

referenceController.$inject = ['$scope'];

var app = angular.module('app',[]).controller('referenceController', referenceController);

app.directive("listItem", function () {
    return {
        restrict: "E",
        scope: false,
        template: "<div>Yo {{formattedText}} {{list.name}}</div>",
        link: function (scope, element, attrs) {
        scope.formattedText = scope.list.name + ' (' + scope.list.abbreviation + ')';
        }
   }
}); 

referenceController.js

function referenceController($scope) {
    $scope.List = [
        { id: 1, name: 'Name1', abbreviation:'1'},
        { id: 2, name: 'Name2', abbreviation: '2'},
        { id: 3, name: 'Name3', abbreviation: '3'},
        { id: 4, name: 'Name4', abbreviation: '4'}
    ];
}

2 个答案:

答案 0 :(得分:2)

formattedText并非难以推导,因此您只需将其放入模板中即可:

template: "<div>Yo {{list.name}} ({{list.abbreviation}}) {{list.name}}</div>"

答案 1 :(得分:1)

您需要在指令中观察值:

referenceController.$inject = ['$scope'];

var app = angular.module('app',[]).controller('referenceController', referenceController);

app.directive("listItem", function () {
  return {
    restrict: "E",
    scope: false,
    template: "<div>Yo {{formattedText}} {{list.name}}</div>",
    link: function (scope, element, attrs) {
      var formatText = function(value){
        scope.formattedText = value + ' (' + scope.list.abbreviation + ')';
      }

      formatText(scope.list.name)
      scope.$watch('list.name',formatText)
    }
 }
});