如何通过 angular 中的函数更新视图

How to update view via function in angular

在下面的示例中,我编写了一个函数,它在默认值 $scope.word 下工作正常,但是当我更新视图或输入时,它不会更新控制器中的 $scope,因此它不会反映返回查看。不确定这里的数据绑定和摘要循环是如何工作的。谢谢,

html:

<div class="container" ng-controller="myCtrl">
    <textarea rows="10" cols="50" ng-model="word"></textarea>
    <br>
    {{word}}
    <ul>
        <li ng-repeat="(key, value) in obj">{{key}} : {{value}}</li>
    </ul>
    <dir text="largetext"></dir>
</div>

js:

var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', ['$scope', function($scope){

    $scope.obj = {}
    $scope.word = "d a c a d a b c b b c b d d";
    var str = $scope.word.trim().replace(/[\.\,\']/g,"").split(" ");
    function wordCount(str) { 
        var _obj = {}
        str.forEach(function(word){
            (word in _obj) ? _obj[word]++ : _obj[word] = 1
        })
        return _obj;
    }
    $scope.wordCount = wordCount;
    console.log($scope.wordCount(str));
    $scope.obj = wordCount(str); 

}])

here is jsfiddle link.

这是工作代码::

<div class="container" ng-controller="myCtrl">
    <textarea rows="10" cols="50" ng-model="word" ng-change="wordCount()"></textarea>
    <br>
    {{word}}
    <ul>
        <li ng-repeat="(key, value) in obj">{{key}} : {{value}}</li>
    </ul>
    <dir text="largetext"></dir>
</div>


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

myApp.controller('myCtrl', ['$scope', function($scope){

    $scope.obj = {}
    $scope.word = "d a c a d a b c b b c b d d";
    function wordCount() { 
    var str = $scope.word.trim().replace(/[\.\,\']/g,"").split(" ");
        $scope.obj = {}
        str.forEach(function(word){
            (word in $scope.obj) ? $scope.obj[word]++ : $scope.obj[word] = 1
        })
        return $scope.obj;
    }
    $scope.wordCount = wordCount;
    console.log($scope.wordCount());
    $scope.obj = wordCount(); 
}])

Demo

演示代码

<div class="container" ng-controller="myCtrl">
    <textarea rows="10" cols="50" ng-change="wordCount(word)" ng-model="word"></textarea>
    <br>
    {{word}}
    <ul>
        <li ng-repeat="(key, value) in obj">{{key}} : {{value}}</li>
    </ul>
    <dir text="largetext"></dir>
</div>


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

myApp.controller('myCtrl', ['$scope', function($scope){

    $scope.obj = {}
    $scope.word = "d a c a d a b c b b c b d d";

    $scope.wordCount = function(str) { 
  str = str.trim().replace(/[\.\,\']/g,"").split(" ");
        $scope.obj = {}
        str.forEach(function(word){
            (word in $scope.obj) ? $scope.obj[word]++ : $scope.obj[word] = 1
        })    
    }       
  $scope.wordCount($scope.word);
}])