替代在“查看”使用NG-INIT? [英] Alternative to using ng-init in 'view'?

查看:96
本文介绍了替代在“查看”使用NG-INIT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建我的应用程序一个喜欢功能。我希望能够设置动态生成数的值作为喜欢计数。问题出现在使用'NG-初始化,因为文件说,这是一个糟糕的方​​式来做到这一点!

I am trying to create a 'like' function for my app. I want to be able to set the value of a dynamically generated number as the 'like count'. The problem comes in using 'ng-init', as the documentation says this is a bad way to do it!

你如何在控制器设置的值,而不是视图?

How do you set the value in the 'controller' rather than the 'view'?

下面是我到目前为止有:

Here is what I have so far:

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <script>document.write('<base href="' + document.location + '" />');</script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
  <article ng-repeat="feed in feeds">
    <h3>{{feed.createdby}}</h3>
    <p>{{feed.content}}</p>
    <button ng-click="likeClicked($index)">{{isLiked[$index]|liked}}</button>
    <span ng-init="likeCount=feed.likes.length">{{likeCount}}</span>
  </article>
</body>
</html>

谢谢,

JP

推荐答案

只要修改

`<span ng-init="likeCount=feed.likes.length">{{likeCount}}</span>`

`<span>{{feed.likes.length}}</span>`.

如果您仍然需要在控制器某些其他原因(我看不到)计数,创建一个控制器,让我们假设 FeedCtrl ,并将其添加到你的文章

If you still need the count in the controller for some other reason (which I can't see), create a controller, let's assume FeedCtrl, and add it to your article:

<article ng-repeat="feed in feeds" ng-controller="FeedCtrl">
  ...
  <span>{{likeCount}}</span>
</article>

和您的FeedCtrl将是:

And your FeedCtrl would be:

function FeedCtrl($scope) {
  $scope.$watch('feed.likes.length', function(newValue) {
    $scope.likeCount = newValue;
  });
}

另一种方法将是创建一个功能,以解决将值:

Yet another approach would be create a function to resolve you the value:

<article ng-repeat="feed in feeds" ng-controller="FeedCtrl">
  ...
  <span>{{likeCount()}}</span>
</article>

function FeedCtrl($scope) {
  $scope.likeCount = function() {
    return $feed && $feed.likes ? $feed.likes.length : undefined;
  };
}

这篇关于替代在“查看”使用NG-INIT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆