2017-02-25 70 views
0

我是新來AngularJs。我已經開發了具有MVVM方法的KnockoutJs。您可以在ViewModel中定義數據,並在View中定義數據。這樣,您可以創建模塊化和單一用途的可重用控件,以基於ViewModel的輸入顯示任何數據。如何在AngularJs中實現它?如何給輸入到角控制器

我讀到scope,這我覺得是數據視圖和控制器之間結合的角度的方式。內部控制器,無論您分配給範圍,都可以在View中使用。

然而,如何給輸入到控制器,以便它可以隨後將處理這反過來將得到顯示在搜索範圍輸入和地方價值? 例如比方說,我想打一個控制器,它接受一個數字作爲輸入,加1,這個數字並把在$scope.numberPlusOne然後在視圖中,我使用{{numberPlusOne}}以顯示加號?如何實現它,因爲當我們嵌套控制器時會需要它,對嗎?

+0

提供角無版本。據我所知,Angular 1仍然很受歡迎。 https://docs.angularjs.org/api/ng/directive/form有你所有的答案。在您的快速示例中,您是否提交了一個表單,它將一個數字作爲輸入,讓控制器添加1,然後將該變量放入範圍中?有點不清楚。 – SirUncleCid

+0

我使用角1 –

+0

我真是一個假設的例子中,我還沒有編碼的呢。 –

回答

0

您可以可以用它來從控制器

$scope.function(elementName){ 
angular.element("'[name="+elementName+"]'").val(''); 
} 
0

這樣就能夠解決您的問題訪問輸入?
我不知道KnockoutJs,但我可以給你的角度1.x的例子。

在View:

<div ng-controller="numberCtrl"> 
    <button type="button" ng-click="plusOne()">Plus One</button><br> 

    <input type="number" ng-model="inputNumber" /> 
    <button type="button" ng-click="plusInput(inputNumber)">Plus One</button><br> 

    <p>{{numberPlusOne}}</p><br> 
    <p>{{numberContainer.plusNumber}}</p><br> 
    <h1>Above code is parent scope</h1> 

    <number-panel load-container="numberContainer"></number-panel> 

</div> 

在控制器:

app.controller('numberCtrl', numberCtrl); 

numberCtrl.$inject = ['$scope', ...]; 

function numberCtrl($scope, ...) { 

    $scope.inputNumber = 0; 

    $scope.numberContainer = { 
     "plusNumber": $scope.inputNumber, 
     // "minusNumber": null 
    }; 

    $scope.numberPlusOne = 0; 

    $scope.plusOne(){ 
     $scope.numberPlusOne ++; 
    } 

    $scope.plusInput(num){ 
     $scope.numberPlusOne += num; 
    } 

} 

在指令:

.directive('numberPanel', function() { 
    return { 
     templateUrl: 'views/template/number.directive.html', 
     scope: { 
      loadContainer: '=', 
     }, 
     replace: true, 
     restrict: 'EA', 
     controller: function ($scope, $element, $attrs) { 
      // here can access $scope.numberContainer through $scope.loadContainer 
      // also you can create other child functions here 
      $scope.plusThree = function(){ 
       $scope.loadContainer.plusNumber += 3 
      } 
     } 
    }; 
}); 

在number.directive.html

<div> 
    <h1>Child Scope</h1> 
    <p>{{ loadContainer.plusNumber }}</p><br> 
    <button type="button" ng-click="plusThree()">Plus Three</button> 
</div> 

$rootScope也是另一種方式來使用跨範圍的對象,但最好不要污染它..

裁判:https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope
計算器:$on and $broadcast in angular

+0

在這裏,你已經將默認值初始化爲0,對吧?相反,如果您需要將它作爲控制器功能的輸入?讓我們說一些其他控制器(也許這個控制器的父母)發送它的價值?我們如何實現這一目標? –

+0

編輯帖子以處理嵌套範圍時使用指令,請參閱https://docs.angularjs.org/guide/directive。 – stackoverYC