2016-07-06 6 views
-2

私はangularJSを初めて使用しており、特定モデルに$watchを追加する方法がわかりません。 angularjsのチュートリアルに行くとき、私はいくつかの問題に直面しています。私はコメントの部分に疑問を述べました。これを通過してください。

(function(angular) { 
angular.module('controllerAsExample', []) 
    .controller('SettingsController1', SettingsController1); 

function SettingsController1() { 
    this.name = "John Smith"; 
    this.contacts = [ 
    {type: 'phone', value: '408 555 1212'}, 
    {type: 'email', value: '[email protected]'} ]; 
} 
//how to add $watch to ng-model 'settings.name' 
/*$scope.$watch("settings.name", function(oldval, newval){ 
    console.log(oldval + " + " + newval); 
});*/ 

SettingsController1.prototype.greet = function() { 
    console.log(this.name); 
}; 


})(window.angular); 

HTMLコード..あなたが実証されていない、あなたのコード内のいくつかの他の機能がない限りここで

<body ng-app="controllerAsExample"> 
    <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings"> 
    <label>Name: <input type="text" ng-model="settings.name"/></label> 
    <button ng-click="settings.greet()">greet</button><br/> 
    </div> 
</body> 

は私のlink

+1

あなたは$ウォッチを追加したい理由は? – Ajay

答えて

0

をチェックし、あなたは)($ウォッチを必要としません。

$ watch()は、angularJSの中で最も悪用される機能の1つです。 AngularJSを初めて使う多くの開発者は、コードを複雑にする不必要な$ watch()式を追加します。

$ watch()を使用するコントローラは、通常、コードの匂いが悪いです。間違いなくあなたは$ watchを使うべき場所がありますが、あなたの例ではこれは一つではありません。

代わりに次の操作を行うことができます。

(function(angular) { 
 
angular.module('controllerAsExample', []) 
 
    .controller('SettingsController1', SettingsController1); 
 

 
function SettingsController1() { 
 
    this.name = "John Smith"; 
 
    this.contacts = [ 
 
    {type: 'phone', value: '408 555 1212'}, 
 
    {type: 'email', value: '[email protected]'} ]; 
 
} 
 

 
SettingsController1.prototype.greet = function() { 
 
    console.log(this.name); 
 
}; 
 

 
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="controllerAsExample"> 
 
    <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings"> 
 
    <label>Name: <input type="text" ng-model="settings.name"/></label> 
 
    <button ng-click="settings.greet()">greet</button><br/> 
 
    </div> 
 
</div>

+0

私は入力フィールドに '$ watch'をします。それは何らかの目的のために必要です。 – htoniv

+1

元の質問を更新して、$ watchを使用する理由を説明できますか?あなたがしようとしている「何」と「なぜ」を説明してください。これは、質の高い回答を得るのに役立ちます。 – Martin

1

基本的に、あなたは$scopeコンテキストを注入する必要があります。このSO answerに記載されています。

function SettingsController1($scope) { 
    this.name = "John Smith"; 
    this.contacts = [ 
    {type: 'phone', value: '408 555 1212'}, 
    {type: 'email', value: '[email protected]'} ]; 

    $scope.$watch(angular.bind(this, function() { 
    return this.name; 
    }), function (newVal, oldVal) { 
    console.log('Name changed to ' + newVal + ', old value = ' + oldVal); 
    }); 
} 

注意$scopeをウォッチャ右コンテキストを伝える機能コントローラ、次いでangular.bind(thisに渡されます。

の作業例: http://plnkr.co/edit/HR0DTphdBsF2xXUfmwfT?p=preview

関連する問題